jQuery getJSON works locally, but not cross domain

You need to look in to JSONP.

Essentially, when you try to load JSON from another domain, it fails because there is a domain boundary you can not cross. To avoid this, you have to PAD it (P in JSONP). Padding it is essentially wrapping it in a function call (where the function name resides on your client.) e.g. a “normal” JSON response (say, for example, getjson.php):

{foo:'bar'}

JSON with a callback of parseJSON becomes (Say, for example, getjson.php?callback=parseJSON):

parseJSON({foo:'bar'})

Notice how the value that was supplied in callback becomes the name of the function your JSON response is now wrapped in.

Then your client will want to pass it to parseJSON, a function that exists on your client (that you’ve defined). jQuery (and other libraries) try to take care of this for you by generating some “random” function and then sending the response back through your original callback (all this is done under the hood).

If you have control over the server page generating the JSON, implement a callback method so you can supply how the JSON should be wrapped so you can then work with it on your end. (This is only necessary when you’re dealing with data from a domain other than the page the client is currently on).


UPDATE

To basically solve the problem you’re having, you need to find a way to get your JSON information in to a JSONP call. Without knowing what language your “page.json” is in, here’s the pseudo-code logic that it should contain:

if GET_VARIABLE("callback") is supplied

  print GET_VARIABLE("callback") and an open parenthesis
  print normal JSON data
  print closing parenthesis

else

  print normal JSON data

end if

If you decide to hard-code the function name instead of allow it to be supplied in the url as “callback”, then you need to remember it. For the next example, let’s imagine we named it MyJSONPCallback

Now, in your client code, you can go ahead of use:

$.ajax({
  url: 'http://anotherdomain.com/page.json?format=json',
  dataType: 'json',
  jsonpCallback: 'MyJSONPCallback', // specify the callback name if you're hard-coding it
  success: function(data){
    // we make a successful JSONP call!
  }
});

Leave a Comment