Analysis of JSONP cross-origin principle, jsonp cross-Origin

Source: Internet
Author: User

Analysis of JSONP cross-origin principle, jsonp cross-Origin

JavaScript is a front-end dynamic script technology that is frequently used in Web development. In JavaScript, there is a very important security restriction, called "Same-Origin Policy" (Same-Origin Policy ). This Policy imposes significant limitations on the page content that JavaScript code can access, that is, JavaScript can only access content in the same domain as the document containing it.

JavaScript, a security policy, is particularly important in Multi-iframe or Multi-Window Programming and Ajax programming. According to this policy, the JavaScript code contained in the page under baidu.com cannot access the page content under the google.com domain name; even pages of different subdomain names cannot be accessed through the JavaScript code. The effect on Ajax is That Ajax requests implemented through XMLHttpRequest cannot submit requests to different domains, for example, pages under abc.example.com cannot submit Ajax requests to def.example.com.

However, when some in-depth front-end programming is required, cross-origin operations are inevitable. At this time, the "same-origin policy" is too harsh. JSONP cross-origin GET requests are a common solution. Let's take a look at how JSONP cross-origin is implemented and discuss the principles of JSONP cross-origin.

The method used to create a <script> node on the page to submit HTTP requests to different domains is called JSONP. This technology can solve the problem of cross-origin Ajax request submission. The working principle of JSONP is described as follows:

If you submit a GET request to http://example1.com/index.php on the page http://example2.com/getinfo. php, we can put the following JavaScript code on the page http://example1.com/index.php to implement the following:

var eleScript= document.createElement("script");eleScript.type = "text/javascript";eleScript.src = "http://example2.com/getinfo.php";document.getElementsByTagName("HEAD")[0].appendChild(eleScript);

When a GET request is sent from.

JSONP has the following advantages: it is not subject to same-origin policy restrictions as Ajax requests implemented by XMLHttpRequest objects; it has better compatibility and can be run in older browsers, XMLHttpRequest or ActiveX is not required. After the request is completed, you can call callback to return the result.

The disadvantage of JSONP is that it only supports GET requests but not POST and other types of HTTP requests. It only supports cross-origin HTTP requests, it cannot solve the problem of how to call JavaScript between two pages in different domains.

Another example:

Var qsData = {'searchword': $ ("# searchWord "). attr ("value"), 'currentuserid': $ ("# currentUserId "). attr ("value"), 'conditionbean. pageSize ': $ ("# pageSize "). attr ("value")}; $. ajax ({async: false, url: http: // cross-domain dns/document! SearchJSONResult. action, type: "GET", dataType: 'jsonp', jsonp: 'jsoncallback', data: qsData, timeout: 5000, beforeSend: function () {// jsonp mode this method is not triggered. the reason may be that if dataType is specified as jsonp, it is no longer an ajax event}, success: function (json) {// The client-side jquery pre-defined callback function, after obtaining the json data on the Cross-origin server, the callback function if (json. actionErrors. length! = 0) {alert (json. actionErrors);} genDynamicContent (qsData, type, json);}, complete: function (XMLHttpRequest, textStatus) {$. unblockUI ({fadeOut: 10}) ;}, error: function (xhr) {// jsonp mode this method is not triggered. the cause may be that if dataType is specified as jsonp, it is no longer an ajax event. // request error processing alert ("request error (please check the relevant network status .) ");}});

Sometimes you can see the following statement:

$. GetJSON ("http: // cross-domain dns/document! SearchJSONResult. action? Name1 = "+ value1 +" & jsoncallback =? ", Function (json) {if (json. attribute name = value) {// Execution Code }});

This method is actually an advanced encapsulation of the $. ajax ({...}) api in the previous example. Some underlying parameters of $. ajax APIs are encapsulated and invisible.

In this way, jquery is assembled into the following url get request:

Http: // cross-domain dns/document! SearchJSONResult. action? & Jsoncallback = jsonp1231627957501 & _ = 1236828192549 & searchWord = % E7 % 94% A8 % E4 % BE % 8B & currentUserId = 5351 & conditionBean. pageSize = 15

On the response side (http: // cross-domain dns/document! SearchJSONResult. action), through jsoncallback = request. getParameter ("jsoncallback") gets the js function name: jsonp1231627957501 to be called back by the jquery end, and then the content of response is a Script Tags: "jsonp1231627957501 (" + json array generated by Request Parameters + ")"; jquery dynamically loads and calls this js tag through the callback method: jsonp1231627957501 (json array ); in this way, cross-Origin data exchange is achieved.

JSONP Principle

The most basic principle of JSONP is to dynamically Add a <script> tag, while the src attribute of the script tag has no cross-domain restrictions. In this case, this cross-origin method is not related to the ajax XmlHttpRequest protocol.

In this way, the "jQuery AJAX cross-origin problem" becomes a pseudo proposition, and the jquery $. ajax method name is misleading.

If it is set to dataType: 'jsonp', the $. ajax method has nothing to do with ajax XmlHttpRequest, and is replaced by the jsonp protocol. JSONP is an unofficial protocol that allows the server to integrate Script tags to return to the client and implement cross-origin access through javascript callback.

JSONP is JSON with Padding. Due to the same-origin policy restrictions, XmlHttpRequest only allows requests to resources of the Current Source (domain name, protocol, port. For cross-origin requests, we can use the html script tag to perform cross-origin requests, and return the script code to be executed in the response, where javascript objects can be directly transmitted using JSON. This cross-origin communication method is called JSONP.

JsonCallback function: jsonp1231627957501 (...): it is registered by the browser client. After obtaining the json data on the Cross-origin server, the callback function

The Jsonp execution process is as follows:

Register a callback (for example, 'jsoncallback') on the client, and send the callback name (for example, jsonp1231627957501) to the server. Note: After the server receives the callback value, it must use jsonp1231627957501 (...) to include the json content to be output. In this case, the server can generate json data to be correctly received by the client.

Then, a function is generated in javascript syntax. The function name is the value of the passed 'jsoncallback' parameter jsonp1231627957501.

Finally, place the json data directly in the function as an input parameter. In this way, a js syntax document is generated and returned to the client.

The client browser parses the script tag and executes the returned javascript document. In this case, the javascript document data is passed as a parameter to the client's pre-defined callback function (jquery $. success: function (json) encapsulated by ajax () method.

It can be said that the jsonp method and <script src = "http: // cross-origin /... xx. js "> </script> is consistent (QQ space is used in large quantities to achieve cross-Origin data exchange ). JSONP is a Script Injection action, so it has certain security risks.

Why does jquery not support cross-origin post?

Although the use of post + dynamic iframe can achieve the purpose of post cross-origin (there is a js cool who just put jquery1.2.5 in this way), this is an extreme method, it is not recommended.

It can also be said that the cross-origin of the get method is legal, and the post method is considered illegal from the security point of view.

The demand for cross-origin access on the client side also attracted w3c's attention. It is said that the html5 WebSocket standard supports cross-Origin data exchange and should also be an optional cross-Origin data exchange solution in the future.

Here is a simple example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  

Among them, jsonCallback is registered by the client. After obtaining json data on the Cross-origin server, it calls back the function. Http://crossdomain.com/jsonServerResponse? Jsonp = jsonpCallback: this url is the interface for the cross-origin server to retrieve json data. The parameter is the name of the callback function. The returned format is jsonpCallback ({msg: 'This is json data '})

Briefly describe the principle and process: first register a callback on the client, and then pass the callback name to the server. In this case, the server is converted into json data. Then, a function is generated in javascript syntax. The function name is the passed parameter jsonp. Finally, place the json data directly in the function as an input parameter. In this way, a js syntax document is generated and returned to the client.

The client browser parses the script tag and executes the returned javascript document. In this case, the data is passed into the pre-defined callback function of the client as a parameter. (Dynamic execution callback function)

From: JSONP cross-origin principle parsing a Script Injection Behavior

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.