当我实际上是console.log(this.collection.fetch())时,您可以在responceJSON和responseText中看到它从api返回了正确的数据。
但是,我的readyState始终保持为1,当我运行时
this.collection.fetch({
success : function() {
console.log(that.collection.toJSON())
}
});
它返回一个空白数组,即使我们没有服务器响应数据。
这是我的代码......
模型
define(['backbone'], function(backbone){
var google_place = Backbone.Model.extend({
defaults : {
'title' : 'no titile',
'sub_title' : 'no subtitle',
'content' : 'no content available',
'lat' : 0,
'lng' : 0,
'text' : 'no text'
}
});
return google_place;
});
收藏
define(['../model/google_place'], function(google_place){
var google_places = Backbone.Collection.extend({
model: google_places,
initialize: function(models, options) {
},
url: function() {
return "http://globallcoach-app.dev/api/";
},
parse: function(data) {
return data.items;
},
});
return google_places;
});
查看
define(includes(), function(backbone, mustache){
var index = Backbone.View.extend({
initialize : function() {
this.template = mustache.render(nav);
},
render : function() {
var that = this;
console.log(that.collection.fetch());
this.collection.fetch({
success : function() {
console.log(that.collection.toJSON())
},
});
return;
},
});
return index;
});
来自fetch(responseText)的JSON响应
[{
"title": "no titile",
"sub_title": "no subtitle",
"content": "no content available",
"lat": "0",
"lng": "0",
"text": "no text"
}, {
"title": "Example Title",
"sub_title": "Example Subtitle",
"content": "Loads on content here",
"lat": "0",
"lng": "0",
"text": "random text bullshit"
}]
答案 0 :(得分:2)
您的集合parse
方法包含以下内容:
parse: function(data) {
return data.items;
},
但响应没有items
属性:
[{
"title": "no titile",
"sub_title": "no subtitle",
"content": "no content available",
"lat": "0",
"lng": "0",
"text": "no text"
}, {
"title": "Example Title",
"sub_title": "Example Subtitle",
"content": "Loads on content here",
"lat": "0",
"lng": "0",
"text": "random text bullshit"
}]
因此parse
返回undefined,collection.toJSON()
返回空数组
您应该删除parse
方法,否则您的回复应为
{
"items": [{
"title": "no titile",
"sub_title": "no subtitle",
"content": "no content available",
"lat": "0",
"lng": "0",
"text": "no text"
}, {
"title": "Example Title",
"sub_title": "Example Subtitle",
"content": "Loads on content here",
"lat": "0",
"lng": "0",
"text": "random text bullshit"
}]
}
此外,您的收藏集似乎并未导入backbone
。确保它可以访问Backbone
并且不会抛出任何错误
答案 1 :(得分:2)
删除解析功能。 JSON已经是一个google_places数组。