jQuery Cross Domain Access Solution Principle Case Explanation

  • 2021-07-02 23:11:01
  • OfStack

Cross-domain access to js on the browser side is a problem. Most R&D personnel treat js with a good scar and forget the pain, so when the disease occurs, it hurts from time to time. I remember that a long time ago, iframe plus script domain declaration and yahoo js util were used to solve the problem of cross-domain access of level 2 domain names.

Time flies, and when it is pulled back to the battlefield of js, the scar of cross-domain problem hurts again. Fortunately, with the help of jQuery, cross-domain problems seem less difficult. This time, I also took this opportunity to find out the root of the cross-domain problem. Combined with the actual development project, I consulted the relevant information, which solved the cross-domain problem. . . It is necessary to write down the memo. Cross-domain security restrictions refer to the browser side. There is no cross-domain security restriction on the server side, so the work of "cross-domain access" is completed by the local server side in a way similar to httpclient, and then the url corresponding to "cross-domain access" on the local server side is obtained by AJAX on the browser side. It is also possible to indirectly complete cross-domain access. However, it is obvious that the development volume is relatively large, but the restrictions are the least. Many widget open platforms server (such as sohu blog open platform) are actually engaged in it. It is beyond the scope of this discussion. What we want to discuss is the real cross-domain access on the browser side. It is recommended that jQuery $. ajax () supports get cross-domain, which is actually done by 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 dataType If specified as jsonp Words , It's no longer ajax Events  
}, 
success: function (json) {// Client jquery Predefined callback Function , Object on the cross-domain server was successfully obtained json After data , Will execute this dynamically callback Function  
if(json.actionErrors.length!=0){ 
alert(json.actionErrors); 
} 
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 specified as jsonp Words , It's no longer ajax Events  
// Request error handling  
alert(" Request error ( Please check the correlation network status .)"); 
} 
});

Note: $. getJSON ("http://Cross-domain dns/document! searchJSONResult. action? name1= "+ value1 +" & jsoncallback=?",


function(json){ 
if(json. Attribute name == Value ){ 
//  Execute code  
} 
}); 

This method is actually an advanced encapsulation of the above example $. ajax ({..}) api, and 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=%E7%94%A8%E4%BE%8B I tUserId=5351&conditionBean.pageSize=15 

On the response side (http://cross-domain dns/document! searchJSONResult. action),

js function name: jsonp 1236827957501 to be subsequently called back at jquery end via jsoncallback = request. getParameter ("jsoncallback")

Then the content of response is one Script Tags: "jsonp 1236827957501 (" + json array generated by request parameters + ")";

jquery dynamically loads and calls this js tag: jsonp 1236827957501 (json array) through the callback method;

In this way, the purpose of cross-domain data exchange is achieved.

The basic principle of jsonp is to dynamically add 1 < script > Tag, and the src attribute of the script tag has no cross-domain restrictions. In this way, this cross-domain approach has nothing to do with ajax XmlHttpRequest protocol.

In fact, "jQuery AJAX cross-domain problem" becomes a false proposition, and jquery $. ajax method name is misleading.

If 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, which allows Script tags to be integrated on the server side and returned to the client side, and cross-domain access is realized through JavaScript callback

JSONP is JSON with Padding. Due to the restriction of the homology policy, XmlHttpRequest only allows requests for 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 we can pass the javascript object directly using JSON.

This cross-domain communication is called JSONP.

jsonCallback function jsonp1236827957501 (...): It is a function registered by the browser client and called back after obtaining json data on the cross-domain server

Jsonp Principle:

First register an callback on the client (e.g. 'jsoncallback') and pass the name of the callback (e.g. jsonp 1236827957501) to the server.

At this point, the server generates json data.

Then, in the way of javascript syntax, an function is generated, and the name of function is the value jsonp1236827957501 of the passed parameter 'jsoncallback'.

Finally, the json data is directly put into function in the way of input parameters, so a document of js syntax is generated and returned to the client.

The client browser parses the script tag and executes the returned javascript document. At this time, the javascript document data, as a parameter, is passed into the callback function predefined by the client (such as success: function (json) encapsulated by the jquery $. ajax () method in the above example). (Dynamic execution of callback function)

It can be said that the way jsonp is in principle and < script src = "http://Cross-domain/... xx. js" > < /script > JSONP is a kind of script injection (Script Injection) behavior, so it also has a certain security risk. (qq space is widely used to realize cross-domain data exchange.) JSONP is a kind of script injection (Script Injection).

Quoted content

Note that jquey does not support cross-domain post mode.

Why?

Although using post + dynamically generating iframe can achieve the cross-domain purpose of post (some js cattle people beat jquery1.2. 5 to patch in this way), it is an extreme way and is not recommended.

It can also be said that the cross-domain of get mode is legal, and the post mode is considered illegal from the security point of view, so don't take a slant as a last resort.

The requirement of cross-domain access at client also seems to attract the attention of w3c. According to the data, html5 WebSocket standard supports cross-domain data exchange, which should also be an optional solution for cross-domain data exchange in the future.

The following is the cross-domain problem resolution of the actual springMVC call restful interface:

1. URL request ends with. jsonp

http://www.test/find.jsonp

2. The Ajax request for Jquery is as follows:


$.ajax({ 
async:false, 
url: url, // Cross-domain dns/document!searchJSONResult.action, 
type: "GET", 
dataType: 'jsonp', 
jsonp: 'callback', 
timeout: 5000, 
beforeSend: function(){ 
//jsonp  This method is not triggered . The reason may be dataType If specified as jsonp Words , It's no longer ajax Events  
}, 
success: function (json) {// Client jquery Predefined callback Function , Object on the cross-domain server was successfully obtained json After data , Will execute this dynamically callback Function  
myFunc(json); 
}, 
complete: function(XMLHttpRequest, textStatus){ 
//$.unblockUI({ fadeOut: 10 }); 
}, 
error: function(xhr){ 
//jsonp  This method is not triggered . The reason may be dataType If specified as jsonp Words , It's no longer ajax Events  
// Request error handling  
alert(" Request error ( Please check the correlation network status .)"); 
} 
}); 

3. Handling business logic in myFunc method

The above is the site to introduce the jQuery cross-domain access to solve the principle of the case detailed description of all, I hope to help you, if you want to know more content please pay attention to this site!


Related articles: