Principle Analysis of Jsonp Cross-domain

Source: Internet
Author: User
Tags domain server
<span id="Label3"></p><p><p>JavaScript is a front-end dynamic scripting technique that is often used in web Development. In javascript, there is a very important security restriction called "same-origin policy" (same-origin strategy). This strategy is an important restriction on the page content that JavaScript code can access, meaning that JavaScript can only access content under the same domain as the document containing it.</p></p><p><p>JavaScript is especially important when it comes to multi-iframe or Multi-window programming, as well as Ajax Programming. According to this strategy, the JavaScript code contained in the page under Baidu.com cannot access the content of the page under the google.com domain name, and even pages between different subdomains cannot be accessed through JavaScript code. The effect on Ajax is that Ajax requests implemented through XMLHttpRequest cannot submit requests to different domains, such as pages under abc.example.com, cannot submit Ajax requests to def.example.com, and so On.</p></p><p><p>however, when doing some more in-depth front-end programming, it is unavoidable to Cross-domain operation, when the "homologous strategy" is too Harsh. JSONP Cross-domain GET request is a common solution, let's take a look at how Jsonp Cross-domain is implemented, and explore the principle of the next Jsonp cross-domain.</p></p><p><p>The method of submitting HTTP requests to different domains with the method of creating <script> nodes in the page is called jsonp, which solves the problem of submitting Ajax requests across Domains. The working principle of JSONP is as Follows:</p></p><p><p>Assuming that a GET request is submitted to http://example2.com/getinfo.php on this page of http://example1.com/index.php, we can put the following JavaScript code in http// example1.com/index.php this page to Implement:</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><pre><span style="color: rgb(0, 0, 255);">var</span> elescript= document.createelement ("script"<span style="color: rgb(0, 0, 0);"></span>= "text/javascript"<span style="color: rgb(0, 0, 0);"></span>= "http://example2.com /getinfo.php "<span style="color: rgb(0, 0, 0);">;d ocument.getelementsbytagname (</span>" HEAD ") [0].appendchild (elescript);</pre></pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p>When a GET request is returned from http://example2.com/getinfo.php, a piece of JavaScript code can be returned, which is executed automatically and can be used to call http://example1.com/ A callback function in the index.php page.</p></p><p><p>The advantage of JSONP is that it is not subject to the Same-origin policy as AJAX requests implemented by XMLHttpRequest objects, that it is better compatible, that it works in older browsers, and that it does not require XMLHttpRequest or ActiveX support , and after the request is complete, the result can be returned by calling Callback.</p></p><p><p>The disadvantage of JSONP is that it only supports get requests and does not support other types of HTTP requests such as post, which only supports Cross-domain HTTP requests, and does not solve the problem of how to make JavaScript calls between two pages in different domains.</p></p><p><p>One more example:</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><span style="color: rgb(0, 0, 255);"><span style="color: rgb(0, 0, 255);">var</span></span>Qsdata = {' Searchword ': $ ("#searchWord"). attr ("value"), ' Currentuserid '<span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);">:$(</span></span>"#currentUserId"). attr ("value"), ' conditionbean.pagesize ': $ ("#pageSize"). attr ("value")<span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);">)};$.ajax ({async:</span></span><span style="color: rgb(0, 0, 255);"><span style="color: rgb(0, 0, 255);">false</span></span><span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);">, url:http:</span></span><span style="color: rgb(0, 128, 0);"><span style="color: rgb(0, 128, 0);">//</span></span><span style="color: rgb(0, 128, 0);"><span style="color: rgb(0, 128, 0);">Cross-domain dns/document!searchjsonresult.action,</span></span>Type: "GET"<span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);">, DataType:</span></span>' Jsonp '<span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);">, Jsonp:</span></span>' Jsoncallback '<span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);">, data:qsdata, timeout:</span></span>5000<span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);">, Beforesend:</span></span><span style="color: rgb(0, 0, 255);"><span style="color: rgb(0, 0, 255);">function</span></span><span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);">(){ </span></span><span style="color: rgb(0, 128, 0);"><span style="color: rgb(0, 128, 0);">//</span></span><span style="color: rgb(0, 128, 0);"><span style="color: rgb(0, 128, 0);">Jsonp Mode This method is not triggered. the reason may be datatype if you specify jsonp, It's not an AJAX event anymore</span> .</span><span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);">}, success:</span></span><span style="color: rgb(0, 0, 255);"><span style="color: rgb(0, 0, 255);">function</span></span>(json) {<span style="color: rgb(0, 128, 0);"><span style="color: rgb(0, 128, 0);">//</span></span><span style="color: rgb(0, 128, 0);"><span style="color: rgb(0, 128, 0);">client jquery pre-defined callback function, after successfully obtaining the JSON data on the Cross-domain server, will execute this callback function dynamically</span></span> <span style="color: rgb(0, 0, 255);"><span style="color: rgb(0, 0, 255);">if</span></span>(json.actionerrors.length!=0<span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);">) {alert (json.actionerrors); } gendynamiccontent (qsdata,type,json); }, complete:</span></span><span style="color: rgb(0, 0, 255);"><span style="color: rgb(0, 0, 255);">function</span></span><span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);">(xmlhttprequest, Textstatus) {$.unblockui ({fadeOut:</span></span>10<span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);"> }); }, error:</span></span><span style="color: rgb(0, 0, 255);"><span style="color: rgb(0, 0, 255);">function</span></span><span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);">(xhr) {</span></span><span style="color: rgb(0, 128, 0);"><span style="color: rgb(0, 128, 0);">//</span></span><span style="color: rgb(0, 128, 0);"><span style="color: rgb(0, 128, 0);">Jsonp Mode This method is not triggered. the reason may be datatype if you specify jsonp, It's not an AJAX event anymore</span> .</span> <span style="color: rgb(0, 128, 0);"><span style="color: rgb(0, 128, 0);">//</span></span><span style="color: rgb(0, 128, 0);"><span style="color: rgb(0, 128, 0);">Request Error Handling</span></span>Alert ("request Error (please check the correlation network condition.)"<span style="color: rgb(0, 0, 0);"><span style="color: rgb(0, 0, 0);">); } });</span></span></pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p><span>Sometimes you will see this:</span></p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><pre>$.getjson ("http//cross-domain dns/document!searchjsonresult.action?name1=" +value1+ "&jsoncallback=?" <span style="color: rgb(0, 0, 0);">, </span> <span style="color: rgb(0, 0, 255);">function</span> <span style="color: rgb(0, 0, 0);">(json) { </span><span style="color: rgb(0, 0, 255);">if</span>(json. property name = = <span style="color: rgb(0, 0, 0);">Value) {</span><span style="color: rgb(0, 128, 0);">//</span><span style="color: rgb(0, 128, 0);"></span><span style="color: rgb(0, 0, 0);"> </span></pre></pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p>This is actually a high-level package of the previous example $.ajax ({..}) api, and some of the $.ajax Api's underlying parameters are encapsulated and not visible.</p></p><p><p>In this way, jquery is assembled into the following URL get request:</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><pre>http:<span style="color: rgb(0, 128, 0);">//</span> <span style="color: rgb(0, 128, 0);">cross-domain dns/document!searchjsonresult.action?&jsoncallback=jsonp1236827957501&_= 1236828192549&searchword=</span>%e7%94%a8%e4%be%8b&currentuserid=5351&conditionbean.pagesize=15</pre></pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p>On the response side (http///cross-domain dns/document!searchjsonresult.action), via jsoncallback = Request.getparameter ("jsoncallback") Get the jquery end to callback the JS function name:jsonp1236827957501 then response content for a script Tags: "jsonp1236827957501 (" + JSON array generated by request parameter + ")"; jquery will invoke this JS tag:jsonp1236827957501 (json Array) dynamically via callback Method. This achieves the purpose of Cross-domain data exchange.</p></p>JSONP principle<p><p>The most basic principle of jsonp is: adding a <script> tag dynamically, and the SRC attribute of the script tag is not a cross-domain Limitation. In this way, this cross-domain approach is actually unrelated to the Ajax XMLHttpRequest Protocol.</p></p><p><p>In fact, "jquery Ajax Cross-domain problem" has become a pseudo-proposition, jquery $.ajax method name is Misleading.</p></p><p><p>If set to Datatype: ' Jsonp ', This $.ajax method has nothing to do with Ajax xmlhttprequest, instead it is the JSONP Protocol. JSONP is an unofficial protocol that allows the Server-side integration of script tags back to the client to achieve Cross-domain access through JavaScript callback.</p></p><p><p>JSONP is the JSON with Padding. Due to the limitations of the Same-origin policy, XMLHttpRequest only allows resources to be requested for the current source (domain name, protocol, port). If Cross-domain requests are made, we can make Cross-domain requests by using the HTML script tag and return the script code to execute in the response, where the JavaScript object can be passed directly using Json. This Cross-domain communication method is called Jsonp.</p></p><p><p>Jsoncallback function jsonp1236827957501 (...) : A callback function that is registered by the browser client and gets the JSON data on the Cross-domain server</p></p><p><p>The JSONP is executed as Follows:</p></p><p><p>First register a callback (for example: ' Jsoncallback ') on the client, and then pass Callback's name (for example: jsonp1236827957501) to the Server. Note: after the server gets the value of callback, use jsonp1236827957501 (...). Include the JSON content that will be output, at which point the server generates JSON data to be properly received by the Client.</p></p><p><p>then, in JavaScript syntax, a function is generated, and the function name is the value jsonp1236827957501 of the parameter ' jsoncallback ' passed up.</p></p><p><p>finally, The JSON data is placed directly into the function in the form of a parameter, so that a document of JS syntax is generated and returned to the Client.</p></p><p><p>The client browser parses the script tag and executes the returned JavaScript document, at which time the JavaScript document data, as parameters, is passed to the Client's pre-defined callback function (as in the previous example, jquery $.ajax () Success:function (json) in the method Encapsulation.</p></p><p><p>Can say Jsonp way principle and <script src= "//cross-domain/...xx.js" ></script> is consistent (qq space is a large number of this way to achieve cross-domain data exchange). JSONP is a script injection (scripts Injection) behavior, So there is a certain security implications.</p></p><p><p>Why does jquery not support the post way cross-domain?</p></p><p><p>Although the use of post+ dynamic generation of IFRAME is possible to achieve the purpose of post Cross-domain (there is a bit of JS cattle is this way to make jquery1.2.5 patch), but this is a more extreme way, not Recommended.</p></p><p><p>can also say get way Cross-domain is legal, post way from security angle, is considered illegal, last but not the sword walk pifo.</p></p><p><p>The need for Client-side Cross-domain access seems to have attracted the attention of the HTML5 WebSocket standard supports Cross-domain data exchange, and should also be a future-selectable cross-domain data exchange Solution.</p></p><p><p>Here's a very simple example:</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><pre><! DOCTYPE HTML Public "-//w3c//dtd XHTML 1.0 transitional//en" "HTTP://WWW.W3.ORG/TR/XHTML1/DTD/XHTML1-TRANSITIONAL.DTD ">

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.