骨干收集是否自动解析加载的数据 [英] Did backbone collection automatically parse the loaded data

查看:61
本文介绍了骨干收集是否自动解析加载的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用主干集合来初始化获取json数据,但事实证明该数据为空. 骨干收集会自动将json数据解析到模型中还是我们必须手动解析它?

Try to use backbone collection to initialize grabbing the json data, but turns out the data is empty. Does backbone collection automatically parse the json data to the model or we have to manually parse it?

 var Book = Backbone.Model.extend({
    title:"",
    isbn:"",
    img:""  
 });

 var Books = Backbone.Collection.extend({
    model:Book,
    url:'latest.json',
    // parse:function(data){
    //  console.log(data);
    // },       
    initialize: function(){
        this.fetch();
    }
 });

经过编辑以添加到示例json中,我通过jsonlint.com进行了验证.

Edited to add in my sample json, I validate with jsonlint.com.

[
    {"title":"American Pie","isbn":"345354356","img":"/image/pie.png"},
    {"title":"Long Tails","isbn":"567575576g","img":"/image/long_tails.png"},
    {"title":"Pirates","isbn":"567575765","img":"/image/pirates.png"}
]

在JSFiddle链接中添加.

Added in JSFiddle link.

http://jsfiddle.net/mochatony/5E3Nc/14/

推荐答案

您需要先确保这些工作正常

You need to make sure these work first

  • 没有脚本错误(在javascript控制台中检查它们)

  • No Script errors ( Inspect them in javascript console)

Collection.fetch请求更正网址(请参阅Chrome网络检查器中的资源部分)

Collection.fetch makes a request to correct url ( see resources section in Chrome web inspector)

检查响应mime/type是否正确"application/json";并且Server确实提供了JSON字符串

Check that response mime/type is right "application/json" and Server indeed serves JSON string

确保JSON响应格式正确(我遇到了这个问题.它必须是数组,而不是对象,例如[{},{},{},{}])

Make sure the JSON response is well formed ( I had this problem . It must be a array and not a object ex : [{},{},{},{}])

最近从服务器刷新(清除缓存)

Lastly refresh from the server ( clear the cache)

这里是一个JsFiddle来演示 http://jsfiddle.net/5E3Nc/16/

Here is a JsFiddle to demonstrate the use http://jsfiddle.net/5E3Nc/16/

注意:仅当要从其构建模型集合的服务器发送自定义响应时,才必须显式地编写解析.

note: Parse must explicitly be written only when custom response is sent from server from which you want to build the models collection

顺便说一句,我注意到你这样做了

by the way, i notices you did this

initialize:function(){
  this.fetch();
}

这是行不通的.您应该在集合本身之外使用集合 例如

this won't work. You are expected to use the collection outside of the collection itself for example

var col = Backbone.Collection.extend({url:"data.json"});
var instance = new col({model:Tweet});
instance.fetch();

这篇关于骨干收集是否自动解析加载的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆