0

I am creating a SPA with Backbone & Underscore JS. The basic feature of the app being that on entering a search term , it needs a trigger an external REST web service call and fetch the JSON response. However when i try this, the browser cancels the request as i guess it tries to make a cross-domain AJAX call.

I am hosting this SPA in my local and the REST web service is hosted on a external server. If i need to make cross-domain calls, what is the procedure which i need to follow without making any changes in the server side? I heard JSONP is one of the alternatives but not sure on the approach.

Ranjith Nair
  • 475
  • 1
  • 6
  • 17

2 Answers2

0

It looks like it is the same problem as in this question. It is pretty useful:

JSONP and Backbone.js

Community
  • 1
  • 1
Dmytro Yarmak
  • 1,018
  • 6
  • 6
0

If your external service supports it already, you are correct that JSONP would be the way to go for cross domain requests without having to change anything on the server side. I assume you're using jQuery. Here's an example from jQuery's docs:

var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
  $.getJSON( flickerAPI, {
    tags: "mount rainier",
    tagmode: "any",
    format: "json"
  })
    .done(function( data ) {
        console.log(data);
    });

You'll notice the ?jsoncallback=? in the flickr URL. That tells flickr to wrap the response in a JSONP callback instead of just returning normal JSON. When flickr sees that, they wrap the response like this:

jQuery19104044632513541728_1395560629443({
        "title": "Recent Uploads tagged mountrainier",
                ...other json data...
});

So instead of returing JSON, they wrap it in a function call which jQuery puts on the global window object. That function call will call your success function with the json data.

Luckily, you don't have to know anything about the inner-workings of it. All you do is call $.getJSON and it'll work!

Prerender.io
  • 1,584
  • 9
  • 9