☮ 12 Jan 2009
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:
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:
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:
http://search.twitter.com/trends.json?callback=handle_data.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:
This is pretty neat, but it does have drawbacks:
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.