Ajax Timeout Verification Script

Source: Internet
Author: User
Tags return

Ajax timeout Verification, the code is as follows:
<script type= "Text/javascript" >
function Ajax () {
var xhr;
if (window. XMLHttpRequest) {
Xhr=new XMLHttpRequest ();
}else{
Try{xhr=new ActiveXObject ("MSXML2"). xmlhttp.6.0 ");} catch (e) {}
Try{xhr=new ActiveXObject ("MSXML2"). XMLHTTP ");} catch (e) {}
}
if (!XHR) return;
This. XHR=XHR; To store an instance of a XMLHttpRequest object with a property
}
Ajax.prototype.send=function (url,options) {
if (!this. XHR) return;
var xhr=this. XHR;
var Aborted=false;
var _options={//provide default value
Method: ' Get ',
timeout:5000,
Onerror:function () {},
Onsuccess:function () {}
};
for (var o in options) {//overwrite the original default value
_options[o]=options[o];
}
function Checkfortimeout () {//Check for timeout
if (xhr.readystate!=4) {
Aborted=true;
Xhr.abort (); Cancel this transmission
}
}
Check the value of the ReadyState property within the specified time
SetTimeout (checkfortimeout,_options.timeout);
function Onreadystatecallback () {
if (xhr.readystate==4) {
/*
* Note: status code in 200 for success, 300 for redirection, 400 is a client error, 500 is a server-side error
*/
if (!aborted && xhr.status>=200 && xhr.status<300) {//Check aborted property timeout
_options.onsuccess (XHR);
}else{
_options.onerror (XHR);
}
}
}
Xhr.open (_options.method,url,true);
Xhr.onreadystatechange=onreadystatecallback;
Xhr.send (NULL);
}
var ajax=new ajax ();
Ajax.send ("test.php", {method:get, timeout:100,onerror:onerror,onsuccess:onsuccess});
function OnError (XHR) {
Alert ("Timeout");
}
function onsuccess (XHR) {
alert (Xhr.responsetext);
}
</script>



Related Article

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.