About Jsonp In Javascript

22:09PM 04/11/2010, Lập trình web

Many people are confused about the use of JSONP. I want to explain the difference between JSON and JSONP in JavaScript.

JSON (JavaScript Object Notation) is a lightweight data-interchange format.
Example of JSON:
{
"firstName": "Vladimir",
"lastName": "Carrer",
"age": 32
}

JSON works well with XmlHttpRequest (AJAJ/AJAX) but the main problem with XmlHttpRequest that is limited with same-domain browser policy. Meaning that you can’t use JSON for remote requests.

For that we have JSONP or "JSON with padding" or remote JSON.

JSONP is a "hack" of JSON in order to make remote request from different domain servers.

Example of JSONP:

AnyNameYouLike ({
"firstName": "Vladimir",
"lastName": "Carrer",
"age": 32
});

In this format(JSONP) can be injected like Script Tag Injection.



Then you call JSONP like this

function AnyNameYouLike (data) {
alert(data.firstName);
}

In order to parse AnyNameYouLike JSONP we have to have function named AnyNameYouLike. 

JSON(P) web service usually provide callback parameter. So it looks like this:

http://someremoteserver.com/jsonp.php?callback=AnyNameYouLike

Meaning that the function name should match with the callback parameter. 

It is important to remember that JSONP is not AJAX and doesn’t use XmlHttpRequest but the script tag.

JSONP is faster than JSON. 

Because JSONP is actually hack to bypass browser security issues is considered not safe.

In the future will probably have something like Cross-Origin Resource Sharing (CORS) that hopefully will provide more safety.

But for now JSONP remains fastest and easiest way to obtain JSON from remote servers with JavaScript.

Let’s build some practical example.

We will use Yahoo YQL to parse reddit.com RSS. YQL will help us to convert RSS to JSONP.

The working Demo. Look at the code.

Did I miss something?

Theo vcarrer.com