What is JSONP? What is the difference between JSON and JSONP?

Solution

We know that JSON is used to transport data. Using $.ajax() or $.getJSON() method you can get the JSON data as response. But what if you have to fetch the data from other domain using AJAX request. For example:- I have domain example.com and I want to fetch JSON data from example1.com using AJAX. This simple approach to fetch JSON data fails if the page is making the ajax calls to different domain. The Same Origin Policy of browser prohibits these type of cross-domain calls in some browser due to security threats.

To overcome this problem JSONP(JSON with Padding) is used. JSONP wraps up a JSON response into a JavaScript function and sends as a Script to the browser/client. The Same Origin Policy is not applied on Script and once the function is loaded it acts like JSON object that it contains.

When a $.getJSON(URL, function) is executed with a URL containing &callback=? JQuery will transparently create the script tag and the handler function. The script tag uses the URL as its src attribute and the handler is created using the function passed as the second argument.

When a $.getJSON(URL, function) is executed with a URL containing &callback=? JQuery will transparently create the script tag and the handler function. The script tag uses the URL as its src attribute and the handler is created using the function passed as the second argument.

$.getJSON("http://example.com/something.json?callback=?", function(result){
   //response data are now in the result variable
});

Share this thread

Comments

Comments
comments powered by Disqus

Navigation

Social Media