Saturday, June 4, 2011

JSONP 101

Definition:
Wikipedia gives such a definition about JSONP:
JSONP or "JSON with padding" is a complement to the base JSON data format, a pattern of usage that allows a page to request data from a server in a different domain. As a solution to this problem, JSONP is an alternative to a more recent method called Cross-Origin Resource Sharing.

Remy sharp defines JSONP in his blog (what is JSONP?) like this:
JSONP is script tag injection, passing the response from server in to a user specified function.

More explanations from wikipedia:
Said a different way, the typical use of JSONP provides cross-domain access to an existing JSON API, by wrapping a JSON payload in a function call.
In that way, the use of JSONP can be said to allow browser pages to work around the same origin policy via script element injection.

Same origin policy:
Wikipedia has the explanation about this policy. Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port or  protocol.

Possible solutions to same_origin_policy:
Proxy (e.g. Nginx)
Script tag
JSONP
CORS (Cross-Origin Resource Sharing)
Flash

Example:
<html>
<head>
<title>JSONP Example</title>
</head>
<body>
<p>Script injection to get a jsonp response from twitter,
and in callback function handleResponse(),
we retrieve the latest tweet from "cnnbrk"</p>
<div id="id"></div>
<script>
function handleResponse(responseJson){   
   //alert(responseJson.status.text);
   //alert(document.getElementById("id"));
   document.getElementById("id").innerHTML = responseJson.status.text;
}
</script>
<script type="text/javascript"
    src="http://twitter.com/users/cnnbrk.json?callback=handleResponse"></script>
</body>
</html>
jQuery and JSONP
jQuery has supported JSONP. For details, see jQuery .ajax() API document, also there is a project on google code http://code.google.com/p/jquery-jsonp/ which is an alternative solution to jQuery's implementation of JSONP. The interface $.jsonp() is similar to $.ajax().

No comments:

Post a Comment