简体   繁体   English

Backbone:从客户端部分的json文件中获取数据

[英]Backbone: fetch the data from a json file which is in the client part

Using Backbone.js , I would like to fetch the data from a Json file in the client part when calling the fetch method on model or collection instance. 使用Backbone.js ,我想在模型或集合实例上调用fetch方法时从客户端部分的Json文件中获取数据。

The url property in my collection ( MyCol ) point to the following json file which looks like this: 我的集合( MyCol )中的url property指向以下json文件,如下所示:

[
  {title: "_My trip to Bali", src: "bali-trip.jpg"},
  {title: "_The flight home", src: "long-flight-oofta.jpg"},
  {title: "_Uploading pix", src: "too-many-pics.jpg"}
]

I perform the following commands: 我执行以下命令:

myCol = new MyCol();
myCol.fetch(); // the Request Method GET is ok 
myCol.toJSON(); // [] 

Remember that fetch is not a synchronous function. 请记住,fetch不是同步函数。 The fetch method will initiate a request to the server and you are alerted to the response through an event or callback. fetch方法将向服务器发起请求,并通过事件或回调向您发出响应警报。

Take a look at the backbone documentation for the fetch method http://documentcloud.github.com/backbone/#Model-fetch . 查看fetch方法http://documentcloud.github.com/backbone/#Model-fetch的主干文档。

Try doing something like this instead. 尝试做这样的事情。

myCol = new MyCol();
myCol.fetch({
    success: function() { //This is fired if the request is succesful
        myCol.toJSON();
    }
});

Or 要么

myCol = new MyCol();
myCol.on('change', function() { //This is fired if the model's attributes change
   myCol.toJSON();
});
myCol.fetch();

Or as @roberkules mentioned, fetch returns a jqXHR , so you could do this. 或者正如@roberkules所提到的,fetch返回一个jqXHR ,所以你可以这样做。

myCol = new MyCol();
myCol.fetch()
     .done(function() {
         myCol.toJSON();
      })
      .fail(function() {
          alert('Oh No!');
      });

@fguillen is right saying you can debug your code simply using success and error callbacks . @fguillen说得对,只需使用success and error callbacks即可调试代码。 Anyway the error is in your json format because of the members which need to be a string. 无论如何,错误是你的json格式,因为成员需要是一个字符串。

Try this and it will work: 试试这个,它会工作:

[
  {"title": "_My trip to Bali", "src": "bali-trip.jpg"},
  {"title": "_The flight home", "src": "long-flight-oofta.jpg"},
  {"title": "_Uploading pix", "src": "too-many-pics.jpg"}
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM