plaintext

JSONP, Quickly

with 11 comments

I discovered JSONP just recently, following Chriscomment. Though I initially didn’t intend to support JSON, JSONP made enough difference that I rewrote most of the TheRealURL code (all 20 lines of it) to support it. Since it took me some time to figure out JSONP initially, perhaps a quick guide might help those who follow.

JSONP allows you to make an HTTP request outside your own domain, which enables consuming Web Services from JavaScript code. It relies on a JS quirk: while XMLHttpRequest is blocked from making external requests, there’s no such limit on <script> elements. What JSONP does is add a <script src=> element to the DOM, with the external URL as the SRC target.

To serve JSONP simply return the JSON data inside a function. e.g., this JSON:

{ "hello" : "Hi, I'm JSON. Who are you?"}

Becomes:

some_function({ "hello" : "Hi, I'm JSON. Who are you?"})

(The reason is that the latter is actually code that will run inside the created by the JSONP client, so it needs to be executable code rather than plain JSON data)

some_function is provided by the calling client, usually in the ‘callback’ parameter. So, a query like this:

get_jsonp?callback=getthedata

Should return:

getthedata({ "hello" : "Hi, I'm JSON. Who are you?"})

On the server side, this means adding some code similar to this:

// assume $json holds the JSON response
if ($GET['callback'] != '') $json = $GET['callback']."( $json )"; 
return $json;   // my PHP is rusty but you know what I mean

On the client side, modern JS frameworks include JSONP support (or you can DIY). For example, in jQuery <= 1.2 adding &callback=? to the query string in getJSON method’s URL sends a JSONP request.(jQuery transparently replaces the ‘?’ with a unique string). Here’s how you get the unshortened URL for ‘bit.ly/a’ using therealurl:

$.getJSON("http://therealurl.appspot.com?format=json&amp;url=bit.ly/q&amp;callback=?", 
	function(data){ alert(data.url) }
);

That’s about it. JSONP probably won’t feature in the next Beautiful Code edition and obviously you need to watch the URLs you’re accessing so you don’t get malicious JS code executed, but, until cross site XHR is resolved, JSONP can get the job done.

Written by niryariv

May 5, 2009 at 2:25 pm

Posted in code, web

11 Responses

Subscribe to comments with RSS.

  1. What you call JSONP has been a standard practice at YAHOO! for some time.

    http://developer.yahoo.com/common/json.html

    One needs to be cautious with this sort of usage though, as you’re essentially trusting a third party to provide you with code. Even if you’re the author of the proxy you could easily suffer from man-in-the-middle attacks if someone can intercept and send you more malicious code.

    Of course, that’s true of all third-party linked javascript.

    Josh Peters

    May 6, 2009 at 5:39 am

    • Thanks Josh! You’re right about security issues, of course.

      Nir

      May 6, 2009 at 9:39 am

    • Not all third-party JavaScript has to be unsafe, as shown in my comment below.

      Elijah Grey

      May 6, 2009 at 2:17 pm

  2. JSONP is very unsafe for XDM. I would rather use either cross-domain XMLHttpRequest, XDomainRequest, or pmxdr

    Elijah Grey

    May 6, 2009 at 2:17 pm

    • That’s definitely the better way – JSONP is really temporary solution until client/server support for cross-origin requests is more widespread.

      Nir

      May 7, 2009 at 9:18 am

  3. [...] JSONP, Quickly I discovered JSONP just recently, following Chris‘ comment. Though I initially didn’t intend to support [...] [...]

  4. I’d recommend $.jsonp rather than $.getJSON or $.ajax. It’s more suited for jsonp than jQuery’s current implementation.

    http://code.google.com/p/jquery-jsonp/

    Julian

    November 6, 2009 at 1:29 am

  5. [...] JSONP output is supported — just throw a ‘&callback=blahblahblah’ on the end of the URL you call and you’ll get a function definition back. [...]

  6. [...] There are a few workarounds for this problem, and Nelson Minar provides a good introduction. You can use proxies, but that’s gross. The most common solution makes use of a loophole in the same-origin policy: you can load JavaScript code from anywhere (just not data). So if you wrap your data so that it looks like code, then you can violate the same-origin policy. If you are providing the data in the JSON format, once wrapped it becomes JSONP. [...]

  7. More information about JSONP work, implementation and usage can be found at http://geekproit.blogspot.com/2011/08/small-research-about-jsonp.html .

    JSONP is good technology. But has it’s own advantages and disadvantages.

    Jen777

    August 17, 2011 at 2:15 pm

  8. [...] created a simple html page that uses JSONP to make cross domain call to twitter’s [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.