This article mainly introduces the in-depth analysis of the JSONP cross-origin principle. For more information, see JavaScript, 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:
The Code is 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 a GET request is sent from.
JSONP has the following advantages:: Unlike the Ajax requests implemented by the XMLHttpRequest object, it is subject to the same-source policy; it has better compatibility and can be run in older Browsers without the support of XMLHttpRequest or ActiveX; after the request is complete, you can call callback to return the result.
The disadvantage of JSONP is that: It only supports GET requests, 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:
The 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 method. This method is not triggered because dataType is no longer an ajax event if it is specified as jsonp.
},
Success: function (json) {// call back function pre-defined by jquery on the client. After obtaining json data on the Cross-origin server, the callback function is dynamically executed.
If (json. actionErrors. length! = 0 ){
Alert (json. actionErrors );
}
GenDynamicContent (qsData, type, json );
},
Complete: function (XMLHttpRequest, textStatus ){
$. UnblockUI ({fadeOut: 10 });
},
Error: function (xhr ){
// Jsonp method. This method is not triggered because dataType is no longer an ajax event if it is specified as jsonp.
// Handle request errors
Alert ("request error (Check related network conditions .)");
}
});
Sometimes you can see the following statement:
The Code is as follows:
$. GetJSON ("http: // cross-domain dns/document! SearchJSONResult. action? Name1 = "+ value1 +" & jsoncallback =? ",
Function (json ){
If (json. attribute name = value ){
// Execute the 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:
The Code is as follows:
Http: // cross-domain dns/document! SearchJSONResult. action? & Amp; jsoncallback = jsonp1231627957501 & amp; _ = 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.
How jsonp works and
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)