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?

JSON stands for JavaScript Object Notation. It is simple a format for representing data, much like XML. Here is some data represented in XML:

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:

  1. You request a JSON document from a remote server and specify a callback parameter. This would look something like http://search.twitter.com/trends.json?callback=handle_data.
  2. 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:

  1. 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 :|
  2. 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?

As a result of this stuff, I did a fun experiment. It grabs the latest trends from Twitter and searches for images tagged with the same at Flickr, all in JS! The source is on Github.