Alex Meub

How does JSONP work?

Standard ( JSON or XML based ) asynchronous web requests are great for lots of applications, but they are crippled because of the same origin policy. You cannot access resources on a domain that is different from the one running your script.

So what if you want to host your content on a different server than your web services? Or load content from a domain you don’t control? For this application there’s JSONP or “JSON with padding”. I think the best way to understand JSONP is in the context of a standard asynchronous HTTP request.

Standard JSON Asynchronous request

  • The browser makes an asynchronous POST request to the server slapping its parameters to the service in the body.
  • The server responds with a string of JSON data.
  • A success handler of the request fires and the string is converted into a Javascript Object to be used in the application.

JSONP Asynchronous request

  • The browser makes an asynchronous GET request to the server slapping its parameters in the request query string including one named “callback”.
  • The server responds with the requested data wrapped in a function call named after the callback parameter. This function call is the “padding” in JSONP.
  • The browser then inserts the server response into the DOM via the <script> tag with JavaScript and this response is immediately run by the browser.
  • Your callback function that you defined before calling the service runs with the JSON data as its parameter. The data does not need to be converted or deserialized.

Here it is using jQuery:

    url: "http://someserver/somejsonpwebservice?param1=hi",
    dataType: "jsonp",
    success: handle_the_data
//somewhere else in the code...
function handle_the_data(data_returned){
    //do stuff with my new object here
    //don't have to deserialize

This is a good example of when jQuery makes things a bit too easy for you - hiding what’s actually going on behind the scenes. You’ll notice there’s no callback parameter in the ajax url, that’s because jQuery handles this automatically and exposes the data to your success function.

To Summarize or TL;DR

JSONP is not magic. It works by dynamically adding a <script> tag to the DOM and calling a predefined function with the remote web service’s JSON data as the parameter. The <script> tag is not subject to the same origin policy and therefore can request content cross-domain.