Wednesday 9 May 2012

JSONP aka JSON with PADDING

JSONP is a hack pattern which allows JavaScript from one domain to execute with JavaScript from another domain. This is technically not allowed as it violates cross-domain polcy, howeber throught the JSO work-aroud it can be acieved. "Why?" I hear you ask, well the answer is simple, someone exposes a service on one machine and you want to consume that service on another. "But that's already possible!" you cry, well yes however you can't execute that service inline, look at the following example: On my.domain.com you have a local script called myscript.js, so the full URL to that script is my.domain.com/myscript.js. Inside this script you want to make a call to other.domain2.com/their.js and execute their JavaScript, it doesn't work, unless you explicitly ue the <script> tags. But that's pointless because you want to execute their inline with yours; that's where JSONP comes in. Using JSONP you are able to overcome this hurdle by setting up an 'understanding' between the service and the requesting JavaScript. This can be achieved by placing a query string parameter in the URL that the service understands, e.g. other.domain.com/their.js?jsonp=yes. The service will 'wrap' it's response in a JavaScript function, which the requesting JavaScript will execute once it's received the request. Once it executes this request, it will hopefully get some meaningful JSON that it can interpret and use for it's own devices.