A workaround for JQuery cross-domain access problems

Source: Internet
Author: User
Tags add time error handling json script tag domain server
Browser-side cross-domain access has always been a problem, most developers treat JS attitude is good scars forget the pain, so when the disease, every now and then to pain on a pain. Remember that a long time ago using iframe Plus script domain declaration, Yahoo JS Util Address the issue of cross-domain access for level two domain names.
Time too fast, and was pulled back to JS battlefield, cross-domain problem this scar again open pain.

Fortunately, with jquery, cross-domain issues seem to be less difficult. This time also take this opportunity to the cross-domain problem to the inquisitive, actual development projects, access to relevant information, is considered to solve the cross-domain problem. It is necessary to write down the memo.

Cross-domain security restrictions are referred to as browser-side. There are no cross-domain security restrictions on the server side.
So through the native server side through a similar httpclient way to complete the "cross-domain Access" work, and then in the browser side with Ajax to get the local server-side "cross-domain Access" the corresponding URL. 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 minimal, Many widgets open platform server side (such as the Sohu Blog open platform) actually do it. Not in the scope of this discussion.

To discuss True cross-domain access on the browser side, it is recommended that jquery $.ajax () currently supports the cross-domain of Get methods, which is actually done in the JSONP way.

Real Case:
Copy the 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 mode This method is not triggered. The reason may be datatype if you specify JSONP, it's not an AJAX event anymore.
},
Success:function (JSON) {//client jquery pre-defined callback function, after successfully acquiring JSON data on a cross-domain server, this callback function is executed dynamically
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 anymore.
Request Error Handling
Alert ("Request error (Please check correlation network status.)");
}
});

Note $.getjson ("http://cross-domain dns/document!searchjsonresult.action?name1=" +value1+ "&jsoncallback=?",
function (JSON) {
if (JSON. property name = = value) {
Execute code
}
});
This is actually a high-level package of the previous example $.ajax ({..}) API, and some of the $.ajax API's underlying parameters are encapsulated and not visible.
This way, jquery is assembled into the URL get request as follows
HTTP//cross-domain dns/document!searchjsonresult.action?&jsoncallback=jsonp1236827957501&_=1236828192549& Searchword=%e7%94%a8%e4%be%8b&currentuserid=5351&conditionbean.pagesize=15

On the response side (HTTP///cross-domain dns/document!searchjsonresult.action),
by Jsoncallback = Request.getparameter ("Jsoncallback"), we get the JS function of the jquery end to be recalled later name:jsonp1236827957501
Then the content of the response is a script Tags: "jsonp1236827957501 (" + by the request parameters generated by the JSON array + ")";
jquery will invoke this JS tag:jsonp1236827957501 (JSON array) dynamically via callback method.
This achieves the purpose of cross-domain data exchange.

The most basic principle of JSONP is: adding a <script> tag dynamically, and the SRC attribute of the script tag is not a cross-domain limitation. In this way, this cross-domain approach is actually unrelated to 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 Ajax XMLHttpRequest, instead it is the JSONP protocol.
JSONP is an unofficial protocol that allows the server-side integration of script tags back to the client to achieve cross-domain access via JavaScript callback
JSONP is the JSON with Padding. Due to the limitations of the same-origin policy, XMLHttpRequest only allows resources to be requested for the current source (domain name, protocol, port). If you want to make cross-domain requests,
We can make cross-domain requests by using the HTML script tag and return the script code to execute in the response, where you can pass the JavaScript object directly using JSON.
This cross-domain communication method is called JSONP.

Jsoncallback function jsonp1236827957501 (...): A callback function that is registered by the browser client and gets the JSON data on the cross-domain server

Jsonp principle:

First register a callback (for example: ' Jsoncallback ') on the client, and then pass callback's name (for example: jsonp1236827957501) to the server.

At this point, the server becomes JSON data.

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

Finally, the JSON data is placed directly into the function in the form of a parameter, so that 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 which time the JavaScript document data, as parameters,
Passed into the client's pre-defined callback function (as in the previous example, the jquery $.ajax () method encapsulates the Success:function (JSON)). (Dynamic execution callback function)

Can say Jsonp way principle and <script src= "//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 script injection (scripts injection) behavior, so there are some security implications.

Note that Jquey is not supported for post-mode cross-domain.
Why is it?
Although the use of post + dynamic generation of the IFRAME is possible to achieve the purpose of post cross-domain (there is a bit of JS cattle is this way to jquery1.2.5 patch), but this is a more extreme way, not recommended.
can also say get way cross-domain is legal, post way from security point of view, is considered illegal, last but not the sword walk Pifo.

The need for client-side cross-domain access seems to have attracted the attention of the HTML5 WebSocket standard supports cross-domain data exchange, and should also be a future-selectable cross-domain data exchange solution.


The script request to return JSON is actually a scripting injection. It solves the cross-domain problem, but it is not omnipotent.

1, cannot accept HTTP status code

2, cannot use post submission (default get)

3, cannot send and accept HTTP headers

4, Cannot set synchronous call (default async)

...

The worst of all is the inability to provide error handling and the correct results if the requested code is executed properly. If the request fails, such as 404,500, then nothing can happen. This article on the basis of the previous article will focus on solving JSONP error handling.

It may be that some browsers can still provide some error handling. If the ie9/10/firefox/safari/chrome supports script's onerror event, the necessary callback processing can be performed on onerror if the request fails. But Ie6/7/8/opera does not support onerror. This is where the headaches are and it's not easy to build a perfect sjax.

As long as the resolution of the Ie6/7/8/opera onerror, the whole is OK. The idea is reverse thinking: the success of the request is a successful callback, or a failure callback. Don't take onerror to say things, because it is not onerror at all. So the only thing that OnLoad said. Is like the following inference:

"You're right," inferred, "you're right."

Because I have no way to know that you are "wrong". But I know you are "right", can only take whether to infer whether you are wrong.

The final implementation details are as follows:

1,ie9/firefox/safari/chrome successful callback using onload event, error callback using OnError event

The 2,opera success callback also uses the OnLoad event (which does not support onreadystatechange at all) and uses deferred processing because it does not support onerror. That is, wait with the success callback success,success after the flag bit done is set to true. Failure is not executed, otherwise it is executed. Here the delay time value is very skilled, before taking 2 seconds, in the company Test no problem. But home with 3G wireless network found that even if the reference JS file exists, but because of slow speed, failure or first executed, after the execution of success. So it's more reasonable to take 5 seconds here. Although this method indirectly realizes the failure, but is not thorough.

3,IE6/7/8 a successful callback using the onReadyStateChange event, the error callback is almost impossible to achieve. It is disgusting that even the requested resource file does not exist (404). Its readystate will also experience a "loaded" state. This way you can't tell the difference between a request's success or failure. Finally, the last challenge is solved by using the coordination mechanism of the front and back stations. Make it call callback (TRUE) whether the request succeeds or fails. At this point the difference between success and failure logic has been put into the callback, if the background does not return JSONP call failure, otherwise call success.

Interface:

Sjax.load (URL, {
Data//Request parameter (key-value pair string or JS object)
Success//Request Success callback function
Failure//Request failed callback function
Scope//callback function execution context
Timestamp//Whether to add time stamp
});

Example:

<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>sjax_0.3.js by snandy</title>
<script src= "Http://files.cnblogs.com/snandy/sjax_0.3.js" ></script>
<body>
<input type= "button" value= "Get Name" onclick= "CLK ()"/>
<script type= "Text/javascript" >
function CLK () {
Sjax.load (' Jsonp66.js ', {
Success:function () {alert (jsonp.name)},
Failure:function () {alert (' Error ');}
});
}
</script>
</body>

Above the HTML, click on the "Get Name" button to invoke the CLK function. Because the requested resource Jsonp66.js does not exist at all. "Error" will pop up under each browser, but there will be some delay in opera. Well, this series is over.

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.