The difference between JSON and JSONP

Source: Internet
Author: User
Tags file url script tag

The difference between JSON and JSONP

First, what is JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format. Easy for people to read and write. It is also easy for machine parsing and generation. It is based on JavaScript programming Language, Standard ECMA-262 a subset of 3rd Edition-december 1999. JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language.

JSON is constructed in two structures:

    • A collection of name/value pairs (A collection of name/value pairs). In different languages, it is understood as objects (object), record (record), structure (struct), Dictionary (dictionary), hash table (hash table), keyed list (keyed list), or associative array (associative array).
    • The sequence of values (an ordered list of values). In most languages, it is understood as an array (array).

These are common data structures. In fact, most of the modern computer languages support them in some form. This makes it possible for a data format to be exchanged between programming languages that are also based on these constructs.

The JSON has these forms:

An object is an unordered collection of "name/value pairs". An object starts with "{" (opening parenthesis) and "}" (the closing parenthesis) ends. Each "name" is followed by a ":" (colon); "' Name/value ' pair ' is separated by", "(comma).

An array is an ordered collection of values (value). An array begins with "[" (the left square bracket), and "]" (the right square bracket) ends. Use "," (comma) to separate values.

The value(value) can be a string enclosed in double quotation marks (string), a numeric value (number), A,,, true object, false null or array. These structures can be nested.

A stringis a collection of any number of Unicode characters surrounded by double quotation marks, escaped with a backslash. A character (character) is a separate string (character string).

A stringis very similar to a C or Java string.

The value(number) is also very similar to the value of C or Java. Removes octal and hexadecimal formats that have not been used. Remove some coding details.

Whitespace can be added to any symbol. The complete language is described below.

Second, what is JSONP

JSONP (JSON with Padding) is a "usage pattern" of data format JSON that allows Web pages to have data from other domains. Another new way to solve this problem is to share resources across sources.

Because of the same-origin policy, Web pages that are generally located in server1.example.com cannot communicate with servers that are not server1.example.com, while HTML <script> elements are an exception. Using this open strategy of <script>, the Web page can get JSON data that is dynamically generated from other sources, and this usage pattern is called JSONP. The data captured with JSONP is not JSON, but arbitrary JavaScript, which executes with a JavaScript interpreter instead of parsing with a JSON parser.

Principle

In order to understand the principle of this mode, first imagine a callback JSON file URL, and JavaScript program can use XMLHttpRequest with this URL to data. Suppose our URL is http://server2.example.com/RetrieveUser?UserId=xxx. Suppose Xiaoming's userid is 1823, and when the browser passes through the URL of Xiaoming, that is, fetch http://server2.example.com/RetrieveUser?UserId=1823, get:

{"Name": "Xiaoming", "Id": 1823, "Rank": 7}

This JSON data can be generated dynamically based on query parameters that pass through URLs.


At this point, it is conceivable to set the SRC attribute of the <script> element to a callback JSON URL, which also represents the possibility of crawling JSON from an HTML page through the script element.

However, a JSON file is not a JavaScript program. In order for the browser to execute in the <script> element, the URL from SRC must be executable JavaScript. In the JSONP usage mode, the URL callback is a dynamically generated JSON that is wrapped up by a function call, which is the origin of JSONP's "Fill (padding)" or "prefix (prefix)".

It is customary for the browser to provide the name of the callback function as part of the named query parameter in the request sent to the server, for example:

<script type= "Text/javascript"
src= "Http://server2.example.com/RetrieveUser?UserId=1823&jsonp=parseResponse" >
</script>

The server will wrap the JSON response with this prefix (or padding) before it is passed to the browser. The response from the browser is not a mere narrative but a script. In this case, the browser gets:

Parseresponse ({"Name": "Cheeso", "Id": 1823, "Rank": 7})

Script element "inject"
In order to start a JSONP callback (or, using this mode), you need a SCRIPT element. Therefore, the browser must add (or reuse) a new <script> element with a SRC value to the HTML DOM-or "inject" the element-for each JSONP. The browser executes the element, crawls the URL in SRC, and executes the JSON of the callback.

And because of this, JSON is called a way to "get users to bypass the same origin policy in the way that the script element is injected."


Security issues
Using the script tag on the remote site will allow the remote site to inject any content into the site. If the remote site has JavaScript injection vulnerabilities, the original site will also be affected.

Now there is an ongoing plan to define the so-called json-p strict security subset so that the browser can enforce the MIME category as "Application/json-p" requests. If the response cannot be resolved to a strict json-p, the browser can throw an error or ignore the entire response.


Cross-site forgery requirements
Rough JSONP deployments are susceptible to cross-site forgery requirements (CSRF/XSRF) attacks. Because HTML <script> tags do not follow the same-origin policy in the browser, malicious Web pages can request and obtain JSON data belonging to other websites. When the user is logged in to that other website, the above situation allows the malicious website to operate the JSON data in the context of a malicious website, potentially revealing the user's password or other sensitive information.

This is only a problem if the JSON data contains hidden data that should not be disclosed to a third party, and the server blocks the abnormal request only by the browser's same-origin policy. If the server itself determines the requirements of the exclusivity, and only when the requirements of normal output data is not a problem. Relying solely on cookies and not enough to determine the requirements is legal, which is susceptible to cross-site forgery requirements.

Apps in JQuery
since the 1.2 release, jquery has added support for JSONP. You can use the $.getjson () method (or other $.ajax ()-based methods) to implement JSON data across domains. Here's an example:


<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>Demo</title>
<script type= "Text/javascript" src= "Jquery.js" ></script>
<script type= "Text/javascript" >
function Do_jsonp () {
$.getjson ("Http://example.com/demo/jsonp.php?type=json&callback=callback_function_name",
function (data) {
$ (' #result '). Val (' data. Image.ids: ' + data. Image.ids);
});
}
</script>
<body>
<a href= "Javascript:do_jsonp (); >click me</a><br/>
<textarea id= "Result" cols= "rows=" 5 "></textarea>
</body>

Note: Http://example.com/demo/jsonp.php?type=json&callback=callback_function_name, callback_function_ in the above example The name will be automatically replaced by jquery with the function name of the callback function (if it is an anonymous function, jquery will automatically generate a time-stamped letter name).

Reference Documentation:

Http://www.json.org/json-zh.html

Http://zh.wikipedia.org/zh-cn/JSONP

Reprint Please specify source: http://blog.exephp.com/?post=4

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.