Pages

Menu

I discovered JSONP just recently, following Chris‘ comment. 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.

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:

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.

14 thoughts on “JSONP, Quickly”

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.