What is the difference between JSON and JSONP ?

JSON (Javascript Object Notation) is a convenient way to transport data between applications. Most of the open APIs provide JSON as a request and response data.

JSON uses the XMLHttpRequest object.

Example

{ "BlogName": "Programmer First", "Category": "Programming" }


JSONP is JSON with padding. The response is JSON data but with a function call wrapped around it. in another way, that is, you put a string at the beginning and a pair of parenthesis around it

functioncall({ "BlogName": "Programmer First", "Category": "Programming" });

JSONP does not use the XMLHttpRequest object.

JSONP uses the <script> tag instead.

Why do we need JSONP

The JSON response from other domains creates cross-domain issues in browsers due to security purposes, To overcome the cross-domain issue we can use the JSONP response, as the script response can be accessed from a different domain.

JQuery has functions that make Ajax/HTTPD requests from a script to a server very easy and $.getJSON() is a great shorthand function for fetching a server response in JSON.

But this simple approach fails if the page making the ajax call is in a different domain from the server. The Same Origin Policy prohibits these cross-domain calls in some browsers as a security measure.

JSONP wraps up a JSON response into a JavaScript function and sends that back as a Script to the browser. A script is not subject to the Same Origin Policy and when loaded into the client, the function acts just like the JSON object that it contains.





Labels: ,