在骨干集合提取中指定xml数据类型

时间:2014-07-15 15:27:10

标签: xml json backbone.js

我正在使用的api返回XML,而骨干网正在期待json数据类型。我可以在我的视图self.collection.fetch()中的某处指定xml数据类型吗?或者这会在我的收藏中完成吗? 代码只是文件的片段。

系列:

define([
'models/routes',
'core'
], function (Routes) {

return Backbone.Collection.extend({

    initialize: function () {},

    model: Routes,      

    url: function (response) {      
        return '/apiproxy.php?method=getroutes';
    },      

 });
});

视图:

define([
'text!html/tplRoutes.html',
'text!html/tplRoute.html',
'collections/routes',
'models/routes',
'core'
], function (template, tplRoute, Routes, Route) {

return Backbone.View.extend({
    el: '',
    template: _.template(template),
    initialize: function () {
        this.collection = new Routes();
    },
    setup: function () {
        var self = this;
        $.when(self.collection.fetch())
            .done(function () {
                console.log(self.collection.toJSON());
                self.render();
            })
            .fail(function (response) {
                console.log(response);
                console.log('request for data has failed');
            });
    },
    render: function () {
    var data = {
        collection: this.collection.toJSON()
    };  
    this.$el.html(_.template(template, data));

    },

PHP代理:

<?php
$url = "http://www.ctabustracker.com/bustime/api/v1/{$_GET['method']}?key=xx";
echo file_get_contents($url);
 ?>

1 个答案:

答案 0 :(得分:0)

Updated collection with: 

url: '/apiproxy.php?method=getroutes',

  parse: function (data) {
    var parsed = [];
        $(data).find('route').each(function (index) {
        var rt = $(this).find('rt').text();
        var rtnm = $(this).find('rtnm').text();
        var rtclr = $(this).find('rtclr').text();
        parsed.push({
            rt: rt, 
            rtnm: rtnm, 
            rtclr: rtclr 
        });        
    });

    return parsed;
},

fetch: function (options) {
    options = options || {};
    options.dataType = "xml";
    return Backbone.Collection.prototype.fetch.call(this, options);
}