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.
The url property
in my collection (MyCol
) point to the following json file which looks like this:
[
{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 mands:
myCol = new MyCol();
myCol.fetch(); // the Request Method GET is ok
myCol.toJSON(); // []
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.
The url property
in my collection (MyCol
) point to the following json file which looks like this:
[
{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 mands:
myCol = new MyCol();
myCol.fetch(); // the Request Method GET is ok
myCol.toJSON(); // []
Share
Improve this question
edited Apr 16, 2013 at 12:18
user2181408
asked May 12, 2012 at 18:04
underscore666underscore666
1,7395 gold badges24 silver badges38 bronze badges
1
-
2
We need more information: 1) Which is the URL of your JSON file? 2) Which is the URL of the Backbone request? 3) What is the Network console showing you? 4) What is something like this
myCol.fetch({ success: function(){ console.log("SUCCESS"); }, error: function(){ console.log("ERROR"); }
showing you? – fguillen Commented May 13, 2012 at 8:27
2 Answers
Reset to default 4Remember that fetch is not a synchronous function. The fetch method will initiate a request to the server and you are alerted to the response through an event or callback.
Take a look at the backbone documentation for the fetch method http://documentcloud.github./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.
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
.
Anyway the error is in your json format because of the members which need to be a string.
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"}
]
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745063806a4609129.html
评论列表(0条)