Use jQuery to solve cross-origin access problems

Source: Internet
Author: User

Cross-origin access on the browser side has always been a problem. Most R & D personnel have a good attitude towards js, and the scars are lost. Therefore, it hurts from time to time when the problem occurs. I remember using iframe and script domain declaration a long time ago. yahoo js util solves the problem of second-level domain name cross-origin access.

When the time passes through and is pulled back to the js battlefield, the cross-domain problem becomes painful again.

Fortunately, with the help of jquery, cross-domain problems seem less difficult. this time, I also took this opportunity to give a thorough understanding of cross-origin issues. Based on the actual development project, I checked the relevant information and solved the cross-origin issue .. it is necessary to write down the memo.

Cross-origin security restrictions refer to cross-origin security restrictions on the browser,
Therefore, the local server uses httpclient-like methods to perform cross-origin access. Then, the browser uses AJAX to obtain the url corresponding to "cross-origin access" on the local server. to indirectly complete cross-origin access. however, it is clear that the development volume is large, but the restrictions are also the least. Many widgets Open Platform servers (such as sohu blog Open Platform) are actually implemented. not in the scope of this discussion.

We will discuss the real cross-origin access on the browser side. We recommend that jQuery $. ajax () currently supports cross-origin access through get, which is actually completed using 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 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 .)");
}
});
Note: $. 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
Http: // cross-domain dns/document! SearchJSONResult. action? & Jsoncallback = jsonp1231627957501 & _ = 1236828192549 & searchWord = % E7 % 94% A8 % E4 % BE % 8B & currentUserId = 5351 & conditionBean. pageSize = 15

On the response side (http: // cross-domain dns/document! SearchJSONResult. action ),
Use jsoncallback = request. getParameter ("jsoncallback") to obtain the js function name: jsonp1231627957501 to be called back by jquery.
Then the response content 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 );
This achieves the purpose of cross-Origin data exchange.

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 issue" becomes a pseudo-proposition. 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. If you want to make a cross-origin request,
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

Jsonp principle:

Register a callback (for example, 'jsoncallback') on the client, and send the callback name (for example, jsonp1231627957501) 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 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 used as a parameter,
Passed to the pre-defined callback function of the client (success: function (json) encapsulated by jquery $. ajax () in the preceding example). (The callback function is dynamically executed)

It can be said that the jsonp method and <script src = "http: // cross-origin /... xx. js "> </script> is consistent (QQ space is used in large quantities to achieve cross-Origin data exchange ). JSONP is a Script Injection action, so it also has certain security risks.

Note that jquey does not support cross-origin post.
Why?
Although the use of post + dynamic iframe can achieve the purpose of post cross-origin (there is a js cool who just put jquery1.2.5 in this way), this is an extreme method, not recommended.
It can also be said that the cross-origin of the get method is legal, and the post method is considered illegal from the security point of view ..

The demand for cross-origin access on the client side also attracted w3c's attention. It is said that the html5 WebSocket standard supports cross-Origin data exchange and should also be an optional cross-Origin data exchange solution in the future.

From: http://www.cnblogs.com/Gaton/

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.