问题
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();
}
});
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"}
]
Added in JSFiddle link.
http://jsfiddle.net/mochatony/5E3Nc/14/
回答1:
You need to make sure these work first
No Script errors ( Inspect them in javascript console)
Collection.fetch makes a request to correct url ( see resources section in Chrome web inspector)
Check that response
mime/type
is right "application/json" and Server indeed serves JSON stringMake 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)
Update
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();
来源:https://stackoverflow.com/questions/10427764/did-backbone-collection-automatically-parse-the-loaded-data