Backbone.js collection call XML file using this.fetch ERROR

帅比萌擦擦* 提交于 2019-12-13 06:14:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!