bmpasini
bmpasini

Reputation: 1503

Backbone JSONP call from RESTful json API not working

I have a RESTful json API, which I need to access in my front-end Backbone site.

So, I did this:

/* 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;
    }
});

I am trying to use JSONP, because it is a different domain. I've followed answers to questions similar to this, as you can see in my code, but it doesn't work.

Instead, I get this error message:

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

What am I doing wrong? How can I make this work?

Upvotes: 0

Views: 157

Answers (1)

user4812626
user4812626

Reputation:

Are you sure that the domain you are trying to access has support for jsonp? Some sites only enable the json format.

Upvotes: 1

Related Questions