来自RESTful json API的Backbone JSONP调用无法正常工作

时间:2015-04-13 23:03:32

标签: javascript backbone.js jsonp

我有一个RESTful json API,我需要在我的前端Backbone站点中访问它。

所以,我这样做了:

/* Goal collection */
var GoalCollection = Backbone.Collection.extend({       
    model: GoalModel,
    url: "http://staging.api.hiwarren.com:8080/api/v1/goals/?callback=?",
    sync: function(method, collection, options) {
        options.dataType = "jsonp";
        // options.timeout = 10000;
        return Backbone.sync(method, collection, options);
    },
    parse: function(response) {
        return response.results;
    }
});
/* View for the goal collection */
var GoalCollectionView = Backbone.View.extend({

    tagName: 'ul',

    initialize: function(callback){
        var that = this;

        _.bindAll(this, 'render');
        that.collection = new GoalCollection();
        that.collection.bind('reset', this.render)

        that.collection.fetch({
            dataType: 'jsonp',
            success: function(collection, response){
                that.render();
                if(callback) callback(that);
            },
            error: function(collection, response){
                throw new Error("Goal fetch error - " + response.statusText);
            }
        });
    },

    render: function(){
        this.collection.each(function(goal){
            var goalView = new GoalView({ model: goal });
            this.$el.append(goalView.render().el);
        }, this);

        return this;
    }
});

我正在尝试使用JSONP,因为它是一个不同的域。我已经按照类似的问题回答了问题,正如你在我的代码中看到的那样,但它不起作用。

相反,我收到此错误消息:

Uncaught Error: Goal fetch error - load
  Backbone.View.extend.initialize.that.collection.fetch.error
  options.errorjquery.js:3094 jQuery.Callbacks.fire
  jQuery.Callbacks.self.fireWithjquery.js:8261 done
  jQuery.ajaxTransport.send.jQuery.prop.on.callback
  jQuery.event.dispatchjquery.js:4116 jQuery.event.add.elemData.handle

我做错了什么?我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

您确定要尝试访问的域是否支持jsonp?某些网站仅启用json格式。