问题
myBook = Backbone.Collection.extend({
initialize: function(models, geturl) {
var self = this;
this.url = geturl;
this.fetch({
dataType: "xml",
async: false,
success: function(collection, xml) {
...
...
...
}
});
}
});
I can't get this to work. Anyone please advise me to solve this problem. I really need to call an XML from the collection. I tried using $.ajax() but failed, so i try using backbone.js function to fetch the XML, but unfortunately i can't get it to work.
Im using:- Backbone.js 0.9.2 & jQuery v1.8.3
Thank you.
回答1:
Backbone expects the server response as JSON. You should override Model.parse with a function that parses the XML and returns a plain Javascript object. jQuery.parseXML is pretty handy for mapping simple XML to an object.
Assuming your XML response would look like this:
<root>
<id>1</id>
<foo bar="foobar">foo</foo>
</root>
And you wanted the model properties to look like:
{
id:1,
foo:'foo',
foobar:'foobar'
}
You could parse it as follows:
var YourModel = Backbone.Model.extend({
parse: function(xml) {
var $xml = $.parseXML(xml);
return {
id: parseInt($xml.find('id').text(), 10),
foo: $xml.find('foo').text(),
foobar: $xml.find('foo').attr('bar')
}
}
});
来源:https://stackoverflow.com/questions/15200745/backbone-js-collection-call-xml-file-using-this-fetch-error