JQuery cross-domain Access problem solving method _jquery

Source: Internet
Author: User
Tags error handling script tag domain server
Time passed quickly, and was pulled back to JS battlefield, cross-domain problem this scar again open pain.

Fortunately, with jquery to help, the cross-domain problem seems to be less difficult. This time also take this opportunity to the cross domain question to the inquisitive, the actual development project, has consulted the related data, is solves 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 through the local server side through a similar httpclient way to complete the work of "Cross-domain access", then, on the browser side, use Ajax to get the URL for "Cross-domain access" on the local server side. It is also possible to indirectly complete cross-domain access. But it is clear that the amount of development is large, but the limit is also minimal, Many widgets open platform server (such as the Sohu Blog open platform) in fact, it is not the scope of this discussion.

To discuss true Cross-domain access on the browser side, it is recommended that the current jquery $.ajax () support get mode Cross-domain, which is actually done in a JSONP way.

Real Case:
Copy Code code 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 This method is not triggered. The reason may be that datatype, if specified as JSONP, is no longer an AJAX event.
},
Success:function (JSON) {//client jquery predefined callback function that dynamically performs this callback function after successfully acquiring JSON data on a 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) {
Jsonp This method is not triggered. The reason may be that datatype, if specified as JSONP, is no longer an AJAX event.
Request Error Handling
Alert (Please check the correlation network condition for errors);
}
});

Note: $.getjson ("http://cross domain dns/document!searchjsonresult.action?name1=" +value1+ "&jsoncallback=?",
function (JSON) {
if (JSON. property name = = value) {
Executing code
}
});
This is actually an advanced encapsulation of the previous example $.ajax ({.}) API, and some $.ajax API low-level parameters are encapsulated and invisible.
This way, jquery is assembled into the following URL get request
http://cross-domain dns/document!searchjsonresult.action?&jsoncallback=jsonp1236827957501&_=1236828192549& Searchword=%e7%94%a8%e4%be%8b&currentuserid=5351&conditionbean.pagesize=15

At the response end (http://cross-domain dns/document!searchjsonresult.action),
Using Jsoncallback = Request.getparameter ("Jsoncallback") to get the JS function that the jquery side will then callback name:jsonp1236827957501
Then response's content is a script Tags: "jsonp1236827957501 (" + JSON array generated by request parameters + ");
jquery dynamically loads the call to this JS tag:jsonp1236827957501 (JSON array) via the callback method;
This achieves the goal of cross domain data exchange.

The basic principle of JSONP is to dynamically add a <script> tag, and the SRC attribute of the script tag is not cross-domain. In this way, this cross-domain approach has nothing to do with the Ajax XMLHttpRequest protocol.
In fact, "jquery Ajax Cross-domain Problem" has become a pseudo proposition, jquery $.ajax method name is misleading.
If set to datatype: ' Jsonp ', this $.ajax method has nothing to do with the Ajax XMLHttpRequest, but instead the JSONP protocol.
JSONP is an unofficial protocol that allows the server-side integration script tags to return to the client, enabling Cross-domain access through JavaScript callback
JSONP is the JSON with Padding. Due to the restriction of the homology policy, XMLHttpRequest only allows resources to be requested for the current source (domain name, protocol, port). If you want to cross domain requests,
We can use HTML script tags for cross-domain requests and return the script code to execute in the response, where you can pass the JavaScript object directly using JSON.
This cross-domain mode of communication is called JSONP.

Jsoncallback function jsonp1236827957501 (...): is the browser client registers, gets the JSON data on the cross domain server, the callback function

Jsonp principle:

First register a callback (such as ' Jsoncallback ') on the client and pass the callback name (such as: jsonp1236827957501) to the server.

At this point, the server is being JSON data.

Then, in JavaScript syntax, a function is generated, and the function name is the value of the parameter ' Jsoncallback ' passed up jsonp1236827957501.

Finally, the JSON data is placed into function directly in the form of a parameter, which generates a document of JS syntax and returns it to the client.

The client browser, parsing the script tag, and executing the returned JavaScript document, at which point the JavaScript document data, as parameters,
Passed into the client's predefined callback function (as in the Success:function (JSON) encapsulated by the jquery $.ajax () method in the example above). (Dynamic execution of callback functions)

It can be said that the principle of Jsonp and <script src= "http://cross-domain/...xx.js" ></script> is consistent (QQ space is a large number of this way to achieve cross-domain data exchange). JSONP is a scripting Injection (script injection) behavior, so there are some security risks.

Note that Jquey is not supported for post-domain cross-domain.
Why, then?
Although the use of post + dynamic generation of IFRAME can achieve the purpose of the post Cross-domain (there is a JS cow is the way to jquery1.2.5 dozen patch), but this is a more extreme way, not recommended.
It can also be said that the cross domain of Get way is legal, post way from the security point of view, is considered illegal, last but not sword walk slant.

The need for client-side Cross-domain access seems to have also attracted the attention of the Global Consortium. HTML5 WebSocket Standard supports Cross-domain data exchange and should also be a future choice for Cross-domain Data interchange solutions.

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.