What is JSONP?
Let’s say you serve up a page to the client and, in addition to the data your server generates, you want to include some data from weather.com. Weather.com has an API limit, though, so your server can’t request that data more than a handful of times in a given period. To get around that limitation, you offload the task to the client; it (attempts) to issue an AJAX request to the weather.com API and now (you hope) you have a million clients hitting the weather.com API with a couple of requests, rather than one server hitting weather.com with two million requests.
Frustratingly, you’re going to bump into a major browser limitation that is the result of an ill-conceived security measure: your browser isn’t allowed to access resources from outside of the domain you’re currently visiting. This is called the same origin policy. Your AJAX request won’t work.
The good news is that someone already figured out a way to get around this limitation. Its called JSONP, short for javascript object notation with padding. It works like this:
Rather than issues an AJAX request, the client dynamically generates a script tag and appends it to the DOM. The script tag has a callback parameter, specified in the querystring at the end of the url. Your script tag will look something like:
<script src=”http://weather.com/jsonp?callback=myCallback13425”></script>
If weather.com supports JSONP, the script it sends back will have the effect of appending the JSON data you requested to your client’s window on the object you specified: myCallback13425. What’s with the random digits at the end of the callback? A random string is always appended to the callback names so that, in the event of multiple JSONP requests to weather.com, subsequent requests don’t overwrite the data your original requests sent back. Make sure you don’t add those digits to the beginning of the callback, though; variable names beginning with numbers are not allowed in javascript!
There are a few more things to do here: you should remove the script tag after your data is loaded and run whatever callback was passed into your JSONP function. But beyond that, you’ve basically gotten the gist of implementing JSONP.: Add a script tag, load your data, and get around the (ineffective) security policies the browser tries to implement.
Side note: If the weather.com server has been compromised, it could easily inject malicious javascript into your client. For this reason, JSONP should only be used with secure, trusted domains.


