An introduction to the principle analysis and implementation of JSONP cross-domain

Source: Internet
Author: User
Tags error handling json script tag domain server

 jsonp Cross-domain Get requests are a common solution, let's take a look at how JSONP is implemented across domains and explore the principles of the next Jsonp cross-domain

JavaScript is a front-end dynamic scripting technique that is often used in web development. In JavaScript, there is a very important security limitation, known as the "Same-origin Policy" (Homology policy). This policy makes a significant restriction on the content of the page that JavaScript code can access, that is, JavaScript can only access content that is under the same domain as the document containing it.     JavaScript This security policy is especially important when it comes to multiple IFRAME or multiple window programming and 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 impact on Ajax is that Ajax requests implemented through XMLHttpRequest cannot submit requests to different domains, such as pages under Abc.example.com, no AJAX requests to def.example.com, and so on.     However, the "homology strategy" is too harsh when it is inevitable that cross-domain operations will be required when more in-depth front-end programming is done. JSONP Cross-domain Get requests are a common solution, let's take a look at how JSONP is implemented across domains and explore the principles of the next Jsonp Cross-domain.     The method of submitting HTTP requests to different domains using the method of creating <script> nodes in the page is called Jsonp, which solves the problem of submitting Ajax requests across domains. The JSONP works as described in the:    hypothesis http://example1.com/index.php this page to http://example2.com/ getinfo.php submit a GET request, we can put the following JavaScript code on the http://example1.com/index.php page to implement the:  code as follows: Var elescript= Document.createelement ("script");  Elescript.type = "Text/javascript";  elescript.src = "http:// example2.com/getinfo.php ";  document.getelementsbytagname (" HEAD ") [0].appendchild (Elescript);    when get requests from http://example2.com/ When Getinfo.php returns, you can return a section of JavaScript code that automatically executes and can be used to invoke a callback function in the http://example1.com/index.php page. The advantage of     JSONP is that it is not limited by the same homology policy as the AJAX request implemented by the XMLHttpRequest object; It is better compatible and can be run in older browsers, No XMLHttpRequest or ActiveX support is required, and the result can be returned by calling callback after the request has been completed. The disadvantage of     JSONP is that it only supports get requests and does not support other types of HTTP requests such as post, it only supports Cross-domain HTTP requests, and does not solve the problem of how to make JavaScript calls between two pages in different domains.   Another example:    code is as follows: 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 Way this method is not triggered. The reason may be that datatype if specified as JSONP, it is not an AJAX event anymore  },  success:function (JSON) {/ Client jquery predefined callback function, successfully obtainedThis callback function   if (json.actionerrors.length!=0) {  alert (json.actionerrors); } are dynamically executed after the JSON data on the Cross-domain server is taken.   Gendynamiccontent (Qsdata,type,json); },  complete:function (XMLHttpRequest, TextStatus) {  $. Unblockui ({fadeout:10}); },  error:function (XHR) { //jsonp This method is not triggered. The reason may be datatype if you specify JSONP, It's not an AJAX event.  //Request error handling   alert ("Request error (Please check correlation network condition.)");  } });  sometimes see such a notation:  $.getjson ("http://dns/document!searchjsonresult.action?name1= across domains" + value1+ "&jsoncallback=?",  function (JSON) {  if (json. property name = = value) { //Execute code  } });    This is actually an advanced encapsulation of the above example $.ajax ({.}) API, and some $.ajax API low-level parameters are encapsulated and invisible.   In this way, jquery is assembled into the following URL get request:  code as follows: http://cross-domain dns/document!searchjsonresult.action?&jsoncallback= jsonp1236827957501&_=1236828192549&searchword= %e7%94%a8%e4%be%8b¤tuserid=5351& conditionbean.pagesize=15    At the response end (http://Cross-domain dns/document!searchjsonresult.action), through JSONcallback = Request.getparameter ("Jsoncallback") gets the JS function that the jquery side will then callback name:jsonp1236827957501 then Response's content is a script Tags: "jsonp1236827957501 (" + JSON array generated by request parameters + "); jquery dynamically loads the call to this JS tag:jsonp1236827957501 (JSON array) via the callback method; This achieves the goal of cross domain data exchange.     JSONP principle   JSONP The most basic principle is: Dynamically add a <script> tag, and the SRC attribute of the script label is not cross-domain restrictions. In this way, this cross-domain approach has nothing to do with the Ajax XMLHttpRequest protocol.   So in fact, "jquery Ajax Cross-domain Problem" has become a pseudo proposition, jquery $.ajax method name is misleading.   If set to datatype: ' Jsonp ', this $.ajax method has nothing to do with the Ajax XMLHttpRequest, but instead the JSONP protocol. JSONP is an unofficial protocol that allows the integration of script tags on the server side back to the client, enabling Cross-domain access through JavaScript callback.     JSONP is JSON with Padding. Due to the restriction of the homology policy, XMLHttpRequest only allows resources to be requested for the current source (domain name, protocol, port). If Cross-domain requests are to be 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 mode of communication is called JSONP.     Jsoncallback function jsonp1236827957501 (...) : is registered by the browser client, after obtaining the JSON data on a cross-domain server, the function     JSONP of the callback is executed as follows:  first registers a callback on the client (e.g. ' Jsoncallback '), Then pass the name of callback (such as: jsonp1236827957501) to the server. Note: After the server gets the callback value,To 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.     Then, in JavaScript syntax, generates a function whose name is the value of the parameter ' Jsoncallback ' passed up jsonp1236827957501 .  finally JSO n data is placed directly into the function in the form of a parameter, which generates a document of JS syntax and returns it to the client.     client browser, parsing the script tag and executing the returned JavaScript document, at which point the JavaScript document data, as parameters, is passed into the client's predefined callback function (jquery $ in the example above). Success:function (JSON) encapsulated by the Ajax () method.   can say Jsonp way principle and <script src= "http://cross-domain/...xx.js" ></script> is consistent (QQ space is a lot of this way to achieve cross-domain data exchange). JSONP is a scripting Injection (script injection) behavior, so there is a certain security risk.   Why does jquery not support post-mode cross-domain?     Although the use of post+ dynamically generated IFRAME can achieve the purpose of the post Cross-domain (there is a JS cow is such a jquery1.2.5 dozen patch), but this is a more extreme way, not recommended.   can also say that the cross domain of Get way is legal, post way from security point of view, is considered illegal, last but not sword walk slant. The need for     client-side Cross-domain access seems to have also attracted the attention of the Global Consortium. HTML5 WebSocket Standard supports Cross-domain data interchange and should also be a future alternative Cross-domain data interchange solution.     to a very simple example:  code is as follows: <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">&nbsp <html xmlns= "http://www.w3.org/1999/xhtml" >  <head>  <title>test jsonp</title>   <script type= "Text/javascript" >  function jsonpcallback (result)   {  alert (result.msg);  }  </script>  <script type= "Text/javascript" src= "http://crossdomain.com/" Jsonserverresponse?jsonp=jsonpcallback "></script>  </head>  <body>  </body >  </html>    Where Jsoncallback is registered by the client, gets the function of the callback after the JSON data on the Cross-domain server is obtained. Http://crossdomain.com/jsonServerResponse?jsonp=jsonpCallback This URL is the interface that takes JSON data across the domain server, and the parameter is the name of the callback function. The format returned is: Jsonpcallback ({msg: ' This is JSON data '})     Brief principle and process: first registers a callback on the client, then passes the callback name to the server. At this point, the server is being JSON data. Then, in JavaScript syntax, a function is generated, and the function name is the parameter Jsonp passed up. Finally, the JSON data is placed into function directly in the form of a parameter, which generates a document of JS syntax and returns it to the client.     client browser, parsing the script tag and executing the returned JavaScript document, where the data is used as a parameter and passed into the client's predefined callback function. (dynamically executing callback functions)    

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.