JSONP Simplified

JSONP is used to get data from remote web locations without running afoul of web browser security restrictions. Browsers prevent access to methods and properties from other domains, with one exception: the <script> tag.  The <script> tag is allowed to reference JavaScript from anywhere. For example, your browser will have no trouble with this script reference, no matter what domain the page is running:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

Servers take advantage of this fact by returning JSON data wrapped in a JavaScript function. The link below asks flickr.com for some images in JSON format. Notice the last query parameter "&jsoncallback=flickrCallback".  The "jsoncallback" property name is determined per server and is typically "callback" or "json". The value "flickrCallback" is the name you give the function that will be returned by the server.  Click this JSONP link to see the basic mechanism in action:

http://api.flickr.com/services/feeds/photos_public.gne?tags=sailing,sunsets&format=json&jsoncallback=flickrCallback

The source for what you get back looks like the screenshot below. Notice the "flickrCallback()" wrapping the data.

kendo017

"flickrCallback" is now available on the page, returns the JSON object with all the JSON goodies you need and can be called anywhere on your page. Here's the complete source for a page that includes the link and a function that uses the callback. The page simply dumps the JSON as text into an element on the page. jQuery is used to easily present JSON as text.

 1: <!DOCTYPE html>
 2: <html xmlns="http://www.w3.org/1999/xhtml">
 3: <head>
 4:     <title>JSONP Sample</title>
 5:     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
 6: </head>
 7: <body>
 8:     <pre><div id="content" /></pre>
 9:  
 10:     <script>
 11: function flickrCallback(data) {
 12: var jsonString = JSON.stringify(data, undefined, 2);
 13:             $("#content").text(jsonString);
 14:         }
 15:     </script>
 16:  
 17:     <script src="http://api.flickr.com/services/feeds/photos_public.gne?" +
 18: "tags=sailing,sunsets&format=json&jsoncallback=flickrCallback"></script>
 19: </body>
 20: </html>

Here is a screenshot of the running example:

kendo019

In case you were wondering, JSONP stands for "JavaScript Object Notation with padding", where the padding is a JavaScript function that wraps JSON data returned from the server.

comments powered by Disqus