Home > Web Front-end > JS Tutorial > In-depth analysis of the principles of JSONP cross-domain_Basic knowledge

In-depth analysis of the principles of JSONP cross-domain_Basic knowledge

WBOY
Release: 2016-05-16 16:27:57
Original
1478 people have browsed it

JavaScript is a front-end dynamic scripting technology often used in web development. In JavaScript, there is a very important security restriction called "Same-Origin Policy". This policy places important restrictions on the page content that JavaScript code can access, that is, JavaScript can only access content in the same domain as the document that contains it.

JavaScript security strategy is particularly important when performing multi-iframe or multi-window programming, as well as Ajax programming. According to this policy, the JavaScript code contained in the page under baidu.com cannot access the content of the page under the google.com domain name; even pages between different subdomains cannot access each other through JavaScript code. The impact 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, etc.

However, when doing some in-depth front-end programming, cross-domain operations are inevitably required. At this time, the "same origin policy" appears to be too harsh. JSONP cross-domain GET request is a common solution. Let's take a look at how JSONP cross-domain is implemented and discuss the principle of JSONP cross-domain.

The method of submitting HTTP requests to different domains by creating <script> nodes in the page is called JSONP. This technology can solve the problem of submitting Ajax requests across domains. JSONP works as described below: </p> <p>Suppose a GET request is submitted to <a href="http://example1.com/index.php">http://example2.com</a>/getinfo.php in the page <a href="http://example2.com">http://example1.com/index.php</a>, we can The following JavaScript code is placed in the page <a href="http://example1.com/index.php">http://example1.com/index.php</a> to implement: </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="12864" class="copybut" id="copybut12864" onclick="doCopy('code12864')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code12864"> <br> var eleScript= document.createElement("script");<br> eleScript.type = "text/javascript";<br> eleScript.src = "<a href="http://example2.com/getinfo.php">http://example2.com/getinfo.php</a>";<br> document.getElementsByTagName("HEAD")[0].appendChild(eleScript);<br> </div> <p>When the GET request returns from <a href="http://example2.com/getinfo.php">http://example2.com/getinfo.php</a>, a piece of JavaScript code can be returned. This code will be automatically executed and can be used to call <a href="http://example1.com/index.php">http: //example1.com/index.php</a>A callback function in the page. </p> <p><strong>The advantage of JSONP is </strong>: It is not restricted by the same-origin policy like the Ajax request implemented by the XMLHttpRequest object; it has better compatibility and can run in older browsers. XMLHttpRequest or ActiveX support is required; and after the request is completed, the result can be returned by calling callback. </p> <p><strong>The disadvantage of JSONP is </strong>: it only supports GET requests but not other types of HTTP requests such as POST; it only supports cross-domain HTTP requests and cannot solve the problem of two pages in different domains. How to make JavaScript calls between. </p> <p>Another example: </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="4578" class="copybut" id="copybut4578" onclick="doCopy('code4578')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code4578"> <br> var qsData = {'searchWord':$("#searchWord").attr("value"),'currentUserId':<br> $("#currentUserId").attr("value"),'conditionBean.pageSize':$("#pageSize").attr("value")};<br> $.ajax({ <br> async:false, <br> URL: http://cross-domain dns/document!searchJSONResult.action, <br> Type: "GET", <br> DataType: 'jsonp', <br> jsonp: 'jsoncallback', <br> Data: qsData, <br> Timeout: 5000, <br> beforeSend: function(){ <br> //This method is not triggered in jsonp mode. The reason may be that if dataType is specified as jsonp, it is no longer an ajax event <br> }, <br> Success: function (json) {//The callback function predefined by jquery on the client side. After successfully obtaining the json data on the cross-domain server, this callback function will be dynamically executed <br> If(json.actionErrors.length!=0){ <br> alert(json.actionErrors); <br>           } <br> ​​​​ genDynamicContent(qsData,type,json); <br> }, <br> Complete: function(XMLHttpRequest, textStatus){ <br>           $.unblockUI({ fadeOut: 10 }); <br> }, <br> error: function(xhr){ <br> //This method is not triggered in jsonp mode. The reason may be that if dataType is specified as jsonp, it is no longer an ajax event <br> //Request error handling <br> alert("Request error (please check the relevance network status.)"); <br> } <br> });<br> </div> <p><strong>Sometimes you will see it written like this: </strong></p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="82552" class="copybut" id="copybut82552" onclick="doCopy('code82552')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code82552"> <br> $.getJSON("http://cross-domain dns/document!searchJSONResult.action?name1=" value1 "&jsoncallback=?", <br> Function(json){ <br> If(json.Attribute name==value){ <br> // Execute code <br> } <br> }); <br> </div> <p>This method is actually an advanced encapsulation of the $.ajax({..}) api in the above example. Some of the underlying parameters of the $.ajax api are encapsulated and not visible. </p> <p>In this way, jquery will be assembled into the following url get request: </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="22073" class="copybut" id="copybut22073" onclick="doCopy('code22073')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code22073"> <br> http://cross-domain dns/document!searchJSONResult.action?&jsoncallback=jsonp1236827957501&_=1236828192549&searchWord=<br> Use case&currentUserId=5351&conditionBean.pageSize=15<br> </div> <p>On the response side (http://cross-domain dns/document!searchJSONResult.action), use jsoncallback = request.getParameter("jsoncallback") to get the js function name to be called back later on the jquery side: jsonp1236827957501 and then the content of the response For a Script Tags: "jsonp1236827957501(" json array generated according to request parameters")"; jquery will dynamically load and call this js tag through the callback method: jsonp1236827957501 (json array); This achieves the purpose of cross-domain data exchange. </p> <p><strong>JSONP Principle</strong></p> <p>The most basic principle of JSONP is to dynamically add a <script> tag, and the src attribute of the script tag has no cross-domain restrictions. In this way, this cross-domain method has nothing to do with the ajax XmlHttpRequest protocol. </p> <p>In this way, "jQuery AJAX cross-domain problem" has become a false proposition. The jquery $.ajax method name is misleading. </p> <p>If set to dataType: 'jsonp', this $.ajax method has nothing to do with ajax XmlHttpRequest, and will be replaced by the JSONP protocol. JSONP is an unofficial protocol that allows integrating Script tags on the server side and returning them to the client, enabling cross-domain access in the form of javascript callbacks. </p> <p>JSONP is JSON with Padding. Due to the restrictions of the same-origin policy, XmlHttpRequest is only allowed to request resources from the current source (domain name, protocol, port). If we want to make a cross-domain request, we can make a cross-domain request by using the script tag of html and return the script code to be executed in the response, where the javascript object can be passed directly using JSON. This cross-domain communication method is called JSONP. </p> <p>jsonCallback function jsonp1236827957501(....): It is registered by the browser client. After obtaining the json data on the cross-domain server, the callback function </p> <p>The execution process of Jsonp is as follows: </p> <p>First register a callback (such as: 'jsoncallback') on the client, and then pass the callback name (such as: jsonp1236827957501) to the server. Note: After the server gets the callback value, it must use jsonp1236827957501(...) to include the json content to be output. At this time, the json data generated by the server can be correctly received by the client. </p> <p>Then use javascript syntax to generate a function. The function name is the value of the passed parameter 'jsoncallback' jsonp1236827957501.</p> <p>Finally, the json data is placed directly into the function as a parameter, thus generating a js syntax document and returning it to the client. </p> <p>The client browser parses the script tag and executes the returned javascript document. At this time, the javascript document data is passed as a parameter to the callback function predefined by the client (such as the jquery $.ajax() method in the above example) Encapsulated success: function (json)). </p> <p>It can be said that the jsonp method is consistent in principle with <script src="http://cross-domain/...xx.js"></script> (qq space uses this method extensively to achieve cross-domain data exchange). JSONP is a script injection (Script Injection) behavior, so it has certain security risks.

Thenwhy doesn’t jquery support cross-domain post?

Although using post to dynamically generate iframe can achieve the purpose of post cross-domain (this is how a js expert patched jquery1.2.5), this is a relatively extreme method and is not recommended.

It can also be said that the cross-domain method of get is legal, and the post method is considered illegal from a security perspective. It is best not to take the wrong approach as a last resort.

The demand for cross-domain access on the client side seems to have attracted the attention of w3c. According to the information, the html5 WebSocket standard supports cross-domain data exchange and should be an optional solution for cross-domain data exchange in the future.

Let’s take a super simple example:

Copy code The code is as follows:

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
http://www.w3.org/1999/xhtml" >

Test Jsonp
%20%0A%20%0A%20%0A%0A%20Among%20them,%20jsonCallback%20is%20the%20function%20registered%20by%20the%20client%20to%20call%20back%20after%20obtaining%20the%20json%20data%20on%20the%20cross-domain%20server.%20
http://crossdomain.com

%20/jsonServerResponse?jsonp=jsonpCallback%20This%20url%20is%20the%20interface%20for%20cross-domain%20servers%20to%20get%20json%20data.%20The%20parameter%20is%20the%20name%20of%20the%20callback%20function.%20The%20returned%20format%20is:%20jsonpCallback(%7Bmsg:'this%20is%20json%20data'%7D)

%0ABrief description of the principle and process: first register a callback on the client, and then pass the callback name to the server. At this point, the server first generates json data. Then use javascript syntax to generate a function. The function name is the passed parameter jsonp. Finally, the json data is placed directly into the function as a parameter, thus generating a js syntax document and returning it to the client. The client browser parses the script tag and executes the returned javascript document. At this time, the data is passed as a parameter to the callback function predefined by the client. (Dynamic execution callback function)

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template