Home  >  Article  >  Web Front-end  >  JSONP cross-domain principle analysis and implementation introduction_javascript skills

JSONP cross-domain principle analysis and implementation introduction_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:54:521114browse

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, JavaScript code contained in pages under baidu.com cannot access page content 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" becomes 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. The working principle of JSONP is as follows: <br><br> Assuming that a GET request is submitted to http://example2.com/getinfo.php in the page http://example1.com/index.php, we can put the following The JavaScript code is placed in the page http://example1.com/index.php to implement: <br></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="93108" class="copybut" id="copybut93108" onclick="doCopy('code93108')"><u>Copy the code </u></a></span> The code is as follows :</div> <div class="codebody" id="code93108"> <br>var eleScript= document.createElement("script"); <br>eleScript.type = "text/javascript"; <br>eleScript.src = "http://example2.com /getinfo.php"; <br>document.getElementsByTagName("HEAD")[0].appendChild(eleScript); <br> </div> <br>When a GET request is made from http://example2.com/getinfo.php When returning, you can return a piece of JavaScript code, which will be automatically executed and can be used to call a callback function in the http://example1.com/index.php page. <br><br>The advantage of JSONP is that 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 without the need for XMLHttpRequest or ActiveX support; and after the request is completed, the result can be returned by calling callback. <br><br>The disadvantages of JSONP are: 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 between two pages in different domains. Issues making JavaScript calls. <br>Another example: <br><div class="codetitle"> <span><a style="CURSOR: pointer" data="84822" class="copybut" id="copybut84822" onclick="doCopy('code84822')"><u>Copy code </u></a></span> The code is as follows: </div> <div class="codebody" id="code84822"> <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) {//Client jquery is predefined callback function, after successfully obtaining the json data on the cross-domain server, this callback function will be executed dynamically <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>Sometimes you will also see this writing: <br>$.getJSON("http://cross-domain dns/document!searchJSONResult.action?name1=" value1 "&jsoncallback=?", <br>function(json){ <br>if(json.property name==value){ <br>//Execute code<br>} <br>}); <br> </div> <br>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 invisible. <br>In this way, jquery will be assembled into the following url get request: <br><div class="codetitle"> <span><a style="CURSOR: pointer" data="62796" class="copybut" id="copybut62796" onclick="doCopy('code62796')"><u>Copy code </u></a></span> The code is as follows: </div> <div class="codebody" id="code62796"> <br>http://cross-domain dns/document!searchJSONResult.action?&jsoncallback=jsonp1236827957501&_=1236828192549&searchWord= <br>Use case¤tUserId=5351&conditionBean.pageSize=15 <br> </div> <br>In response end (http://cross-domain dns/document!searchJSONResult.action), through jsoncallback = request.getParameter("jsoncallback") to get the js function name to be called back later on the jquery end: jsonp1236827957501. Then the content of the response is 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. <br><br>JSONP Principle <br>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. <br>In this way, "jQuery AJAX cross-domain problem" has become a false proposition. The jquery $.ajax method name is misleading. <br>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. <br><br>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. <br><br>jsonCallback function jsonp1236827957501(....): It is registered by the browser client. After obtaining the json data on the cross-domain server, the execution process of the callback function <br><br>Jsonp is as follows: <br>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 obtains 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. <br><br>Then use javascript syntax to generate a function. The function name is the value jsonp1236827957501 of the passed parameter 'jsoncallback'. <br>Finally, place the json data directly into the function as a parameter. This generates a js syntax document and returns it to the client. <br><br>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 jquery $.ajax in the above example) () method encapsulated in success: function (json)). <br>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.
Then why 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 also be an optional solution for cross-domain data exchange in the future.

Let’s take a super simple example:

Copy the code The code is as follows:




Test Jsonp






Among them, jsonCallback is the function registered by the client to call back after obtaining the json data on the cross-domain server. http://crossdomain.com/jsonServerResponse?jsonp=jsonpCallback This URL is the interface for cross-domain servers to obtain 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. 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 of callback function)
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