从RESTful服务查看主干网中的数据

2024-04-27 01:07:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试查看从服务导入的集合,在客户端使用主干,并使用python/flask作为服务。当我发出GET请求时,我得到以下数据:

{"entries": [{"Title": "my title 1", "Description": "My desc 1", "Info": "Info 1", "ids": 1}, {"Title": "my title 2", "Description": "My desc 2", "Info": "Info 2", "ids": 2}]}

但是这些条目不会显示在我的页面上,即使我使用fetch。这是我的ListView代码:

var app = app || {};

app.ContactListView = Backbone.View.extend({
 el: '#contacts',

initialize: function () {

    this.collection = new app.ContactList();
this.collection.fetch({reset: true});
    this.render();
this.listenTo( this.collection, 'reset', this.render );
},


render: function () {
    this.collection.each(function( item ){
    this.renderContact( item );
}, this );
},

renderContact: function ( item ) {
    var contactView = new app.ContactView({
        model: item
    });
    this.$('#ContactTable').append( contactView.render().el );
}
});

原因可能是什么?你知道吗


Tags: infoappidstitlemyfunctiondescriptionfetch
1条回答
网友
1楼 · 发布于 2024-04-27 01:07:06

原因是您的集合需要一个模型数组作为其响应,但您的服务在条目下返回数组。从documentation

parse is called by Backbone whenever a collection's models are returned by the server, in fetch. The function is passed the raw response object, and should return the array of model attributes to be added to the collection.

为了解决这个问题,您可以简单地重写parse方法以返回模型数组。你知道吗

例如:

app.ContactList = Backbone.Collection.extend({
      //...
     parse: function (response) {
         return response.entries;
     } 
})

相关问题 更多 >