JSONP, or JSON with padding, is an extended version of JSON that allows for cross-site AJAX requests. It consists of a string enclosed in parentheses, as seen in the example below:
//JSON {"name":"stackoverflow","id":5} //JSONP func({"name":"stackoverflow","id":5});
JSON data is typically stored as a string, while JSONP is encapsulated within a function call. This allows it to be loaded as a script file.
Both JSON and JSONP share the ".json" file extension.
Cross-Site AJAX: JSONP allows for AJAX requests between different domains. This is accomplished by setting up a function to handle the JSON data once the script file has finished loading.
For instance, if example.com provides JSONP files in the format shown earlier, you can use the following code to retrieve data from that domain, even if your website is not hosted on example.com:
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);
The above is the detailed content of JSON vs. JSONP: What are the Key Differences in Format, File Type, and Use Cases?. For more information, please follow other related articles on the PHP Chinese website!