JQuery cross-domain access solution principle case detailed _jquery

Source: Internet
Author: User
Tags error handling script tag domain server

Browser-side Cross-domain access has been a problem, most developers treat the attitude of JS is a good scar forget the pain, so when the disease, every now and then will hurt a pain. Remember a long time ago, using the IFRAME Plus script domain declaration, Yahoo JS util to solve the problem of cross-domain access of level two domain names.

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 less intractable. 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, and the 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 done through the native server side in a similar httpclient manner, and then the URL of the native server-side Cross-domain access is obtained using AJAX on the browser side. It is also possible to perform cross-domain access indirectly. But it is obvious that the development is relatively large, but the limit is minimal, many widgets open platform server (such as the Sohu Blog open platform) actually do. Not in 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:

var qsdata = {' Searchword ': $ ("#searchWord"). attr ("value"), ' Currentuserid ': $ ("#currentUserId"). attr ("value"), ' Conditionbean.pagesize ': $ ("#pageSize"). attr ("value")};
$.ajax ({ 
async:false, 
url:http://dns/document!searchjsonresult.action across domains, 
type: "Get", 
DataType : ' Jsonp ', 
jsonp: ' Jsoncallback ', 
data:qsdata, 
timeout:5000, 
beforesend:function () { 
//jsonp Way this method is not triggered. The reason may be that datatype is not an AJAX event if specified as Jsonp 
}, 
success:function (JSON) {// Client jquery's predefined callback function, which successfully acquires JSON data on a Cross-domain server, dynamically executes this 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 mode This method is not triggered. The reason may be datatype if you specify JSONP, It's not an AJAX event. 
//Request for error handling 
alert ("Request error (Please check correlation network condition.)"); 
} 
);

Note: $.getjson ("http://cross domain dns/document!searchjsonresult.action?name1=" +value1+ "&jsoncallback=?",

function (JSON) { 
if (json. Attribute name = = value) { 
//execute 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

 
 

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 Cross-domain requests are to be made, we can make cross-domain requests by using the HTML script tag and return the script code to execute in the response, where the JavaScript object can be passed 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, is passed into the client's predefined callback function (for example, the jquery $.ajax () Method encapsulates the Success:function (JSON). (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.

Reference content

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.

The following is the actual SPRINGMVC call to the RESTful interface, which is a cross-domain problem resolution:

1, URL request to the end of. Jsonp

Http://www.test/find.jsonp

2, jquery Ajax request 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 Way this method is not triggered. The reason may be that datatype is not an AJAX event if specified as Jsonp 
}, 
success:function (JSON) {// Client jquery's predefined callback function, which successfully acquires JSON data on a Cross-domain server, dynamically executes this callback function 
MyFunc (JSON); 
Complete: function (XMLHttpRequest, textstatus) { 
//$.unblockui ({fadeout:10}); 
}, 
error:function (XHR) { 
Jsonp way This method is not triggered. The reason may be that datatype if specified as JSONP, it is no longer an AJAX event 
//Request error Handling 
alert ("Request error (Please check correlation network condition.)") 
 

3. Dealing with business logic in the MyFunc method

The above is a small set for you to introduce the jquery Cross-domain access to solve the principle of the full description of the case, I hope to help you, if you want to learn more content please pay attention to cloud habitat community!

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.