Javascript 从JSON文件将数据加载到主干集合中?
我正在尝试使用以下非常基本的代码从本地JSON文件将一些数据加载到主干集合中:Javascript 从JSON文件将数据加载到主干集合中?,javascript,json,backbone.js,Javascript,Json,Backbone.js,我正在尝试使用以下非常基本的代码从本地JSON文件将一些数据加载到主干集合中: window.Student = Backbone.Model.extend({ }); window.Students = Backbone.Collection.extend({ model: Student, }); window.AllStudents = new Students(); AllStudents.fetch({ url: "/init.json"}); c
window.Student = Backbone.Model.extend({
});
window.Students = Backbone.Collection.extend({
model: Student,
});
window.AllStudents = new Students();
AllStudents.fetch({ url: "/init.json"});
console.log('AllStudents', AllStudents);
在console语句中,AllStudents
为空。但是肯定正在加载init.json
。看起来是这样的:
[
{ text: "Amy", grade: 5 },
{ text: "Angeline", grade: 26 },
{ text: "Anna", grade: 55 }
]
我做错了什么
更新:我还尝试在.fetch()
调用上方添加一个重置
侦听器,但也没有触发:
AllStudents.bind("reset", function() {
alert('hello world');
});
AllStudents.fetch({ url: "/init.json"});
不显示任何警报
更新2:尝试此脚本(全文复制):
在第三个fetch()
调用中,甚至只出现一个控制台语句,它是一个空对象
我现在完全困惑了。我做错了什么
JSON文件被用作application/JSON,因此与此无关 我认为您需要在fetch的选项中添加
{add:true}
如果将fetch赋值给变量,也会得到结果,
但是,javascript中的I/O操作几乎总是异步的,主干网也是如此。这意味着仅仅因为
AllStudents.fetch
已经返回,它还没有获取数据。因此,当您点击console.log
语句时,资源尚未提取。您应该将回调传递给fetch
:
AllStudents.fetch({ url: "/init.json", success: function() {
console.log(AllStudents);
}});
或者,也可以选择在jQuery中使用新的承诺功能(fetch
将返回承诺):
fetch()返回一个“success”通知(如前所述),但这仅仅意味着服务器请求成功。fetch()带回了一些JSON,但它仍然需要将其填充到集合中
集合的内容更新后,将触发“重置”事件。此时集合已准备好使用
AllStudents.bind('reset', function () { alert('AllStudents bind event fired.'); });
看起来你在第一次更新中就有了这个。我唯一不同的做法是将fetch()放在事件绑定前面。JSON文件中的属性名称和非数字属性值必须用双引号(“”)括起来。单引号或无引号会产生错误,并且不会创建可用于创建模型和填充集合的响应对象 所以。如果将json文件内容更改为:
[
{ "text": "Amy", grade: 5 },
{ "text": "Angeline", grade: 26 },
{ "text": "Anna", grade: 55 }
]
您应该看到非空的集合对象
您可以更改代码以查看成功和失败,如下所示:
AllStudents.fetch({
url: "/init.json",
success: function() {
console.log("JSON file load was successful", AllStudents);
},
error: function(){
console.log('There was some error in loading and processing the JSON file');
}
});
要了解更多细节,最好查看ajax响应对象的创建方式。Hm——控制台语句从未出现过——就好像从未触发成功一样。
init.json
文件肯定正在加载,不过……我认为这不对-{add:true}
添加而不是替换内容,但我想替换内容。你说得对。这是正确的答案。这是正确的答案。这是一个很好的问题。你应该用它来验证你的JSON
[
{ "text": "Amy", grade: 5 },
{ "text": "Angeline", grade: 26 },
{ "text": "Anna", grade: 55 }
]
AllStudents.fetch({
url: "/init.json",
success: function() {
console.log("JSON file load was successful", AllStudents);
},
error: function(){
console.log('There was some error in loading and processing the JSON file');
}
});