Home > Article > Web Front-end > Use jQuery and JSONP to easily solve cross-domain access problems_jquery
Time flies so fast, and when I am pulled back to the js battlefield, the scar of cross-domain issues starts to hurt again.
Fortunately, with the help of jquery, the cross-domain problem seems not so difficult. This time I also took this opportunity to get to the bottom of the cross-domain problem. Based on the actual development project, I checked the relevant information and finally solved the cross-domain problem. Question..It is necessary to write down the memo.
Cross-domain security restrictions all refer 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 in It is also possible to use AJAX on the browser side to obtain the URL corresponding to the "cross-domain access" on the local server side to indirectly complete cross-domain access. However, it is obvious that the amount of development is relatively large, but the restrictions are also minimal. Many widget open platform servers (such as Sohu blog open platform) is actually just that. It is not within the scope of this discussion.
What we want to discuss is the true cross-domain access on the browser side. It is recommended that jQuery $.ajax() currently supports cross-domain access in the get method, which is actually done using jsonp.
Real case:
$.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. Possible reasons If the 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 successfully obtains the json data on the cross-domain server Afterwards, this callback function will be executed dynamically
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 correlation network status.)" ; Copy the code
The code is as follows:
On the response side (http://cross-domain dns/document!searchJSONResult.action),
get the js function name to be called back later on the jquery side through jsoncallback = request.getParameter("jsoncallback")
Then the content of the response is a Script Tags: "jsonp1236827957501("json array generated according to the 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.
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. </p> <p>If set to dataType: 'jsonp', this $.ajax method has nothing to do with ajax XmlHttpRequest, and will be replaced by the JSONP protocol.</p> <p>JSONP is an unofficial protocol that allows Script tags to be integrated on the server side and returned to the client, and cross-domain access to JSONP, that is, JSON with Padding, can be achieved through javascript callback. 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. </p> <p>jsonCallback function jsonp1236827957501(....): It is registered by the browser client. After obtaining the json data on the cross-domain server, the callback function </p> <p><strong><font style="BACKGROUND-COLOR: #ccffcc">Jsonp principle: </font></strong></p> <p>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. </p> <p>Then use javascript syntax to generate a function. The function name is the value of the passed parameter 'jsoncallback' jsonp1236827957501.</p> <p>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. </p> <p>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> to the callback function predefined by the client (such as jquery $.ajax in the above example) () method encapsulated success: function (json)). (Dynamic execution of callback function) </p> <p>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 also has certain security risks.
Sample code of principle:
Why?
Although using post to dynamically generate iframe can achieve the purpose of post cross-domain, doing so is a relatively extreme method and is not recommended.
It can also be said The cross-domain method of get is legal, but 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 cross-domain data exchange solution in the future