Time flies so fast, and when I was pulled back to the js battlefield, the scar of cross-domain problems started to hurt again.
Fortunately, with the help of jquery, cross-domain problems seemed not so difficult. This time too I took this opportunity to get to the bottom of the cross-domain issue, combined with the actual development project, checked the relevant information, and finally solved the cross-domain issue. It is necessary to write down a memo.
The cross-domain security restrictions are Refers to the browser side. There are no cross-domain security restrictions on the server side.
So the "cross-domain access" work is completed through the local server side through a method similar to httpclient, and then AJAX is used on the browser side to obtain this It is also possible to indirectly complete cross-domain access by using the URL corresponding to the "cross-domain access" on the machine server. However, it is obvious that the development volume is relatively large, but the restrictions are minimal. Many widget open platform server sides (such as Sohu Blog Open Platform) are actually It's not within the scope of this discussion.
What we want to discuss is the real cross-domain access on the browser side. What is recommended is that jQuery $.ajax() currently supports cross-domain access in the get method, which actually uses jsonp
Real case:
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 This method is not triggered. The reason may be that if dataType is specified as jsonp, it is no longer an ajax event
},
success: function (json) {/ /The callback function predefined by jquery on the client side will be dynamically executed after successfully obtaining the json data on the cross-domain server
if(json.actionErrors.length!=0){
alert(json. actionErrors);
}
genDynamicContent(qsData,type,json);
},
complete: function(XMLHttpRequest, textStatus){
$.unblockUI({ fadeOut: 10 });
},
error: function(xhr){
//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
//Request Error handling
alert("Request error (please check the relevance network status.)");
}
});
Note: $.getJSON(" http://cross-domain dns/document!searchJSONResult.action?name1=" value1 "&jsoncallback=?",
function(json){
if(json. Attribute name==value){
//Execution code
}
});
This method is actually an advanced encapsulation of the $.ajax({..}) api in the above example. Some of the underlying parameters of $.ajax api are encapsulated and invisible.
In this way, jquery will be assembled into the following url get request
http://cross-domain dns/document!searchJSONResult.action?&jsoncallback =jsonp1236827957501&_=1236828192549&searchWord=use case¤tUserId=5351&conditionBean.pageSize=15
On the response side (http://cross-domain dns/document!searchJSONResult.action),
through jsoncallback = request.getParameter(" jsoncallback") Get the js function name that will be called back later on the jquery side: jsonp1236827957501
Then the content of the response is a Script Tags: "jsonp1236827957501("json array generated according to the request parameters")";
jquery will pass the callback The method dynamically loads and calls this js tag:jsonp1236827957501 (json array);
This achieves the purpose of cross-domain data exchange.
The most basic principle of jsonp is: 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, the "jQuery AJAX cross-domain issue" has become a false proposition, and the jquery $.ajax method name is misleading. <br>If set to dataType: 'jsonp', this $.ajax method has nothing to do with ajax XmlHttpRequest, and is replaced by the JSONP protocol. <br>JSONP is an unofficial protocol that allows the integration of Script tags on the server side Return to the client and achieve cross-domain access through javascript callback <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, <br> 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. <br>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 callback function <br><br>Jsonp principle: <br><br>First register a callback (such as: 'jsoncallback') on the client, and then pass the callback name (such as: jsonp1236827957501) to the server. <br><br>At this time, the server first generates json data. <br><br>Then use javascript syntax to generate a function. The function name is the value jsonp1236827957501 of the passed parameter 'jsoncallback'. <br><br>Finally, place the json data directly as a parameter. function, 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. <br>The callback function predefined by the client (such as jquery in the above example) The success: function (json) encapsulated by the $.ajax() method. (Dynamic execution of the callback function) <br><br>It can be said that the jsonp method is in principle the same as <script src="http://cross-domain /...xx.js"></script> are consistent (qq space uses this method to achieve cross-domain data exchange). JSONP is a script injection (Script Injection) behavior, so there are Certain security risks.
Note that jquey does not support cross-domain posting.
Why?
Although using post to dynamically generate an iframe can achieve the purpose of post cross-domain (with some js This is how great people patch jquery 1.2.5), but 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 safe from a security perspective. It's illegal. As a last resort, don't go too far.
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, which should be the case. An optional future solution for cross-domain data exchange.