使用this.fetch错误的Backbone.js集合调用XML文件 [英] Backbone.js collection call XML file using this.fetch ERROR

查看:89
本文介绍了使用this.fetch错误的Backbone.js集合调用XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

myBook = Backbone.Collection.extend({
    initialize: function(models, geturl) {
        var self = this;
        this.url = geturl;
        this.fetch({
            dataType: "xml",
            async: false,
            success: function(collection, xml) {
                ...
                ...
                ...
            }
        });
    }
});

我无法使用它.任何人请建议我解决这个问题.我真的需要从集合中调用XML.我尝试使用$ .ajax()但失败了,所以我尝试使用ribs.js函数来获取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.

我正在使用:- Backbone.js 0.9.2& jQuery v1.8.3

Im using:- Backbone.js 0.9.2 & jQuery v1.8.3

谢谢.

推荐答案

Backbone希望服务器响应为JSON.您应该使用解析XML并返回纯Javascript对象的函数覆盖 Model.parse . jQuery.parseXML 对于将简单XML映射到对象非常方便.

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.

假设您的XML响应如下所示:

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'
}

您可以将其解析如下:

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')
    }
  }  
});

这篇关于使用this.fetch错误的Backbone.js集合调用XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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