Is it possible to use javascript to download JSON object from another domain/server?

cross-domain, javascript, jquery, json

Solution

That other domain/server needs to support JSONP, which basically wraps the JSON in a callback.

In jQuery, the call would look like this:

$.getJSON(
     'http://otherdomain.com/api/whatever?callback=?', 
     { key: 'value', otherkey: true },
     function(data){
        //handle response
     }
);

The actual response from the other server (if you looked at what was actually being sent) would look like this:

// With this url:
http://domain.com/api/method?callback=the_callback_function_name

// The response would look like this:
the_callback_function_name({ "json": "data here"});

The jQuery getJSON method automatically handles JSONP when you supply the extra `callback=?`. Just keep in mind some sites using different names like `json_callback=?`. The important part is that you include it as part of the URL and don't try to add `callback: '?'` to the `data` part of the `getJSON` function.

Problem

What would that code look like?

Original source

Related problems