Home >Web Front-end >JS Tutorial >JSON vs. JSONP: What are the Key Differences in Format, File Type, and Use Cases?

JSON vs. JSONP: What are the Key Differences in Format, File Type, and Use Cases?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 22:49:13727browse

JSON vs. JSONP: What are the Key Differences in Format, File Type, and Use Cases?

JSON vs. JSONP: Format, File Type, and Practical Applications

What exactly is JSONP?

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});

Format Differences

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.

File Type Differences

Both JSON and JSONP share the ".json" file extension.

Practical Use Differences

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn