Tag: jquery

What the heck is JSONP?

Posted by – December 9, 2010

I’ve got it working but didn’t know how it works.

To avoid the same origin policy, JSON is a good thing to help you. The thing on the same origin policy is the browser requests from JavaScript or Flash aren’t allowed because we need to protect from script injection attacks. If this happens, the resources like http cookies will be accessed then your authentication or password in the cookies can be stolen.

So we can’t fix this but we can avoid it. The basic idea is we can request any Javascript anywhere.

<script src="http://somewhere/jsfile" type="text/javascript"></script>

Once it loaded, the browser could execute this javascript.

But if it receives json then it does nothing. We can make a returned Javascritpt looks like this.

var json_var = {'var1':'val1'};

It would be better if we can define the callback function.

myCallback({'var1':'val1'});

The server needs to provide this padding. The next thing is we have to declare this function(myCallback) to be executed once it loaded.

For instance, Graph on Facebook allows us to define the callback

https://graph.facebook.com/175459332480559/albums?callback=myCallback

by putting the ?callback=yourCallback at the end of uri

I misunderstood when I started because I saw the doc from jQuery that can put the dataType as jsonp and I thought it was just another asynchronous request which can request across the domain name on the browser.

Basically, jQuery actually provides the callback function as well like

https://graph.facebook.com/19292868552?callback=jsonp1291493679672

jsonp1291493679672 is the callback function to be defined in window like window['jsonp1291493679672'] which defines data and returns this data to the callback function we put in the ajax request. What it does is, jQuery puts ?callback=? at the end of uri and replaces a question mark(?) with jsonp1291493679672. The numbers at the end comes from now() btw.