About JSONP in JavaScript

Thursday, November 04, 2010 { 4 Comments }

Responses to “About JSONP in JavaScript”

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": 32JSON 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.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 thisfunction 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=AnyNameYouLikeMeaning that the function name should match with the callback parameter.JSONP is faster than JSON.Because JSONP is actually hack to bypass browser security issues is consideredIn 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.. Look at the code.Did I miss something?