当我尝试从服务器获取数据到我的Backbone模型时,我遇到了问题。你从JSON
得到了来自服务器的响应,我觉得它的格式正确。你能看到它有什么问题吗?它看起来像:
[{"id":"1","name":"Fawad Hassan","email":"fawad@test.com"},{"id":"2","name":"Bill
Gates","email":"bill@test.com"},{"id":"3","name":"Steve
Jobs","email":"steve@test.com"},{"id":"4","name":"Naveed
Ahmad","email":"naveed@test.com"},{"id":"5","name":"Mr Zee","email":"zee@test.com"}]
我的Backbone项目代码看起来像这样,我也找不到问题。
window.AppModel = Backbone.Model.extend({
url: function() {
return 'http://dev.local/ci/index.php/site/userpost';
}
});
window.AppContr = Backbone.Collection.extend({
model: AppModel,
initialize: function() {
this.model = new AppModel;
}
});
window.App = new AppContr({name: "Markus"});
window.AppView = Backbone.View.extend({
el: $("#content"),
initialize: function() {
this.render();
},
render: function() {
console.log(App.model.toJSON());
}
});
App.model.fetch();
window.View = new AppView;
答案 0 :(得分:8)
您正在对模型执行fetch
,但会在响应中返回Collection。这是主要问题。
第二个问题是你在AppView上调用render
是完全随机的,即它与model
或collection
没有任何关系。也许在渲染视图时model
中没有任何内容。您应该使用collection
将呈现绑定到model
或bind
。每当您致电fetch
时,您的视图都会重新渲染,这是Backbone的主要优势之一:)
代码如下:)
window.Person = Backbone.Model.extend({});
window.Addressbook = Backbone.Collection.extend({
url: 'http://dev.local/ci/index.php/site/userpost',// declare url in collection
model: Person
}
window.Addresses = new AddressBook();
window.AppView = Backbone.View.extend({
el: $('#content'),
initialize: function() {
Addresses.bind('reset', this.render); // bind rendering to Addresses.fetch()
},
render: function(){
console.log(Addresses.toJSON());
}
});
window.appview = new AppView();
Addresses.fetch();