Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between JSON and JSONP?

Format wise, file type wise and practical use wise?

like image 495
Mohammad Avatar asked May 22 '10 06:05

Mohammad


People also ask

What is JSONP used for?

JSONP is a method for sending JSON data without worrying about cross-domain issues. JSONP does not use the XMLHttpRequest object. JSONP uses the <script> tag instead.

What is dataType JSONP?

dataType: jsonp for cross-domain request, that means request to different domain and dataType: json for same domain-same origin request. Loads in a JSON block using JSONP. Adds an extra "? callback=?" to the end of your URL to specify the callback.

Why should we avoid JSONP?

JSONP has some other limitations, too: It can only be used for GET requests, and there's no general way to prevent cross-site request forgeries*. It's bad for private data, since any site on the web could hijack a JSONP response if the URL is known. This means it's best suited for consumption of public data feeds.

What is JSONP API?

JSONP, or JSON-P (JSON with Padding), is a historical JavaScript technique for requesting data by loading a <script> element, which is an element intended to load ordinary JavaScript.


1 Answers

JSONP is JSON with padding. That is, you put a string at the beginning and a pair of parentheses around it. For example:

//JSON {"name":"stackoverflow","id":5} //JSONP func({"name":"stackoverflow","id":5}); 

The result is that you can load the JSON as a script file. If you previously set up a function called func, then that function will be called with one argument, which is the JSON data, when the script file is done loading. This is usually used to allow for cross-site AJAX with JSON data. If you know that example.com is serving JSON files that look like the JSONP example given above, then you can use code like this to retrieve it, even if you are not on the example.com domain:

function func(json){   alert(json.name); } var elm = document.createElement("script"); elm.setAttribute("type", "text/javascript"); elm.src = "http://example.com/jsonp"; document.body.appendChild(elm); 
like image 182
Marius Avatar answered Sep 17 '22 16:09

Marius