What the heck is JSONP?
Published on January 12, 2009 by Jesse Storimer
Recently I stumbled across something called JSONP. I read that it was a hack that allowed for cross domain AJAX requests, which of course piqued my interest, but I had a really hard time finding out how it worked. After spending a few days experimenting and reading blog posts, I think I have a grasp on it.
So here is my attempt at a pop-up book explanation:
What is JSON?
and the same data represented in JSON:
What is JSONP?
JSONP stands for JSON with Padding. It is basically a clever hack that allows for cross domain AJAX requests, but it requires the participation of the remote server you are requesting data from. It works something like this:
- You request a JSON document from a remote server and specify a callback parameter. This would look something like
- This is the part that requires participation from the remote server. If they support JSONP, they will wrap the resulting JSON data in a JS function call, returning a script that looks something like this:
How can I use this?
If you define a callback method in your document and then use a script tag to include a JSONP call, you can request and handle that JSON data, all from JS. Like so:
Yay! Cross domain JS request.
If this went right over your head, as it did for me the first few times, here is a recap:
- You included a remote script (from Twitter in this case) that made a call to a JS function (whose name you specified with the callback parameter) with the JSON data that you wanted as an argument to that function.
This is pretty neat, but it does have drawbacks:
- Danger: You are allowing the remote server to execute arbitrary JS on your page. This is generally a bad idea and you have no way of verifying what that server is embedding in your document. If you trust the server then this technique works just fine :|
- This technique requires that the remote server implement some logic to allow you to do this. This is becoming more prevalent however. Thus far I have discovered that Twitter and Flickr both support this. Anyone find others?