将数据加载到从JSON文件中的骨干集合? [英] Load data into a Backbone collection from JSON file?
问题描述
我想一些数据从本地JSON文件加载到骨干收集,使用这种非常基本的code:
I'm trying to load some data into a Backbone Collection from a local JSON file, using this very basic code:
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);
在控制台中陈述, AllStudents
是空的。但 init.json
绝对是加载。它看起来是这样的:
In the console statement, AllStudents
is empty. But init.json
is definitely being loaded. It looks like this:
[
{ text: "Amy", grade: 5 },
{ text: "Angeline", grade: 26 },
{ text: "Anna", grade: 55 }
]
我在做什么错了?
What am I doing wrong?
更新:我也尝试添加重置
监听器 .fetch以上()
打电话,但是这不费一枪之一:
UPDATE: I've also tried adding a reset
listener above the .fetch()
call, but that's not firing either:
AllStudents.bind("reset", function() {
alert('hello world');
});
AllStudents.fetch({ url: "/init.json"});
中不会显示警报。
No alert appears.
更新2 :尝试这个脚本(全部在这里转载):
UPDATE 2: Trying this script (reproduced here in full):
$(function(){
window.Student = Backbone.Model.extend({
});
window.Students = Backbone.Collection.extend({
model: Student,
});
window.AllStudents = new Students();
AllStudents.url = "/init.json";
AllStudents.bind('reset', function() {
console.log('hello world');
});
AllStudents.fetch();
AllStudents.fetch({ url: "/init.json", success: function() {
console.log(AllStudents);
}});
AllStudents.fetch({ url: "/init.json" }).complete(function() {
console.log(AllStudents);
});
});
只有一个控制台声明甚至出现在第三取()
调用,它是一个空的对象。
Only one console statement even appears, in the third fetch()
call, and it's an empty object.
我现在绝对是百思不得其解。我在做什么错了?
I'm now absolutely baffled. What am I doing wrong?
该JSON文件被当作application / JSON,所以它没有任何关系的。
The JSON file is being served as application/json, so it's nothing to do with that.
推荐答案
在您的JSON文件属性名和非数字的属性值必须用双引号()。单引号或无引号产生错误并且响应对象不创建可用于创建模型和填充集合
The attribute names and non-numeric attribute values in your JSON file must be double quoted (" ") . Single quotes or no-quotes produces errors and response object is not created that could be used to create the models and populate the collection.
所以。如果更改JSON文件的内容:
So. If you change the json file content to :
[
{ "text": "Amy", grade: 5 },
{ "text": "Angeline", grade: 26 },
{ "text": "Anna", grade: 55 }
]
您应该看到非空的集合对象。
you should see the non-empty collection object.
您可以更改code看到成功和失败如下:
You can change your code to see both success and failure as below:
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创建响应对象是个好主意。
For more details, probably it will be a good idea to look in to the way ajax response objects are created.
这篇关于将数据加载到从JSON文件中的骨干集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!