Fetching static JSON files cross site with jQuery.

Say you have a static JSON file sitting on a web server, e.g. mystaticfiles.com/hello.json on Amazon S3 or a CDN. For the sake of argument, let’s imagine that it’s a configuration file. The contents of the file looks like this:

{"message": "Hello, world!"}

You want your web application on example.com to fetch data from the static JSON file using Javascript, but you can’t because of cross site constraints. Normally you’d set up a JSONP service write a simple function in Javascript that returns your data, and host the script file (.js) on mystaticfiles.com, which is easy to do (full stop) in e.g. PHP, but you can’t do that because the server doesn’t support server side scripting.

Note: I realize that this solution is just a little over-engineered. If you don’t have anything better to do, go ahead…

Here is the obvious solution in jQuery, written down because you have to use special options in jQuery.

Step one: Add static JSONP padding to you JSON file

Come up with some unique function name, and add it to the static file. The file now looks like this:

skipking541934132({"message":"Hello, world!"});

Step two: Tell jQuery to use the function name

Normally jQuery will come up with a random name for the JSONP callback, and make a request that looks like this:

http://mystaticfiles.com/hello.json?callback=jQuery2348327482374893232

But by using the jsonCallback option we can override that callback function name, to match the function name in the static JSON file.

$.ajax({
  url: "http://mystaticfiles.com/hello.json",
  dataType: "jsonp",
  jsonpCallback: "skipking541934132", /* Unique function name */
  success: function(data){
    /* Do something with data */
    alert(data.message) /* Will alert Hello, world! */ 
  }
});

jQuery will now issue a request that looks like this:

http://mystaticfiles/hello.json?callback=skipking4327894312

Of course the server just throws away the query string, because there is no server side logic to handle it. But inside you web application jQuery has now injected a function called skipking4327894312 that sits there ready to receive your static JSON data.

3 Replies to “Fetching static JSON files cross site with jQuery.”

Leave a Reply