Dealing with static JSONP and jQuery

More and more content on the web requires the use of JSON to build web apps. jQuery and Mootools both provide simple methods for taking that data and parsing it.

$.ajax({url: 'data.json' ,dataType: "json",cache: false }).success(function(data) {
//do stuff with data
});

Now this works fine with json files that are on the server as the result gets bound to the call and can be used with success. However if you are calling data from an external domain you have to use JSONP.

The issue with JSONP is that it doesn't get bound to the call in the same. It injects a script tag into your page and fires off a function. Services such as Twitter and Flickr will generate that callback so the above method will still work. However if you are serving up flat data off a CDN or any other server you aren't going to be able to do that.

A typical JSON file looks like this:
{
"items" : [
{
"name" : "image title",
"image" : "image-01.jpg"
},
{
"name" : "image 2",
"image" : "image-02.jpg"
}
]
};

Let's say, the json file is hosted on an s3 bucket and the script that is making the call is on 2c2d.co.uk. The request will fire but it will be blocked by the browser due to security restrictions.

To get this to work our JSON call will have to look like this :

$.ajax({url: purl,dataType: "jsonp",cache: false,jsonp:'onJsonPLoad' });

We will then need to define what our callback function is going to be both in the JSON file and the script file.

This function is going to be called "processImages".

In script.js
$.ajax({url: purl,dataType: "jsonp",cache: false,jsonp:'onJsonPLoad' });

function processImages(data)
{
// I can take data and it will have my JSON object to manipulate
}

in images.json

processImages({
"items" : [
{
"name" : "image title",
"image" : "image-01.jpg"
},
{
"name" : "image 2",
"image" : "image-02.jpg"
}
]
});

When the request is sent out to the json file on the s3 bucket, it will load the data into the page then fire the processImages function.
I hope this helps people as the documentation on dealing with JSONP is unclear when handling json files that are static.