JSONP: JSON with Padding

March 6, 2009 § Leave a comment

JSONP is a technique allowing JavaScript-only calls to an external server without the need for a proxy to make the call.

JSONP is JSON with Padding. A JSONP call is made to manipulate the host web page’s DOM to dynamically add a script tag. This script tag will remove the server endpoint (REST/Web Service).

This process involves adding a callback method to the query string of the JSONP request. The Javascript method appends the callback method to the body response. The response is wrapped as a parameter to the callback method, similar to the concept of “padding”.

JSONP has many advantages over makeRequest call in MySpace OpenSocial APIs. makeRequest creates more network trips and may trigger multiple points of failure.

JSONP is restricted to GET call only on MySpace Canvas Surface only.. It is restricted to JSON data. JSONP is a hack that is quick and easy to make cross-domain requests from JavaScript.

The drawback is it is difficult to debug JSONP requests.

/**
* Create a JSONP request
* @param {object} url
* @param {object} callback
*/
function makeJsonpRequest (url, callback) {
var jsonpurl = url + “&callback=” + callback;
var e = document.getElementsByTagName (“jsonp”)[0];
var s = document.createElement(“script”);
s.src = jsonpurl;
e.appendChild(s);
}

Advertisements

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 )

Google+ photo

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

Connecting to %s

What’s this?

You are currently reading JSONP: JSON with Padding at Web Builders.

meta

%d bloggers like this: