Backbone.js - 从 url 获取 JSON [英] Backbone.js - Getting JSON back from url
问题描述
在尝试学习 Backbone.js 时,我一直在尝试使用以下代码获取 JSON 文件的内容:
While trying to learn Backbone.js, I've been trying to grab the content of a JSON file using the following code:
(function($){
var MyModel = Backbone.Model.extend();
var MyCollection = Backbone.Collection.extend({
model : MyModel,
url: '/backbone/data.json',
parse: function(response) {
console.log(response);
return response;
}
});
var stuff = new MyCollection;
console.log(stuff.fetch());
console.log(stuff.toJSON());
})(jQuery)
'stuff.fetch()' 返回整个对象(包含我在 responseText 中查找的数据),'stuff.toJSON' 不返回任何内容 ([]),但是 parse 方法中的控制台返回的正是我想要的想要(我的数据的 json 对象).
'stuff.fetch()' returns the entire object (with the data I'm after in responseText), 'stuff.toJSON' returns nothing ([]), but the console in the parse method is returning exactly what I want (the json object of my data).
我觉得我在这里遗漏了一些明显的东西,但我似乎无法弄清楚为什么我无法获得正确的数据.有人可以指出我正确的方向或告诉我我在这里做错了什么吗?我是否将模型用于错误的事情?
I feel like I'm missing something obvious here, but I just can't seem to figure it out why I can't get the right data out. Could someone point me in the right direction or show me what I'm doing wrong here? Am I using a model for the wrong thing?
推荐答案
fetch
是一个异步调用,所以如果你想得到响应,传递一个 success
回调进入论点.
fetch
is a asynchronous call, so if you want to get the response, pass a success
callback into the arguments.
stuff.fetch({
success: function (collection, response) {
console.log(response);
}
})
更多关于 Backbone.js 主页
这篇关于Backbone.js - 从 url 获取 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!