People who have used jquery know that the $.ajax inside can set the timeout processing and throw out all kinds of errors, which is really useful. Native JS does not have a corresponding method, but also to write a variety of compatibility. In practical application, whether the request is successful or not should do fault-tolerant processing,
Otherwise the user does not know what exactly happened, the experience is very bad. Timeout is a situation, it is impossible to request the failure of the user in that silly waiting, is no one can stand. The following describes the time-out processing using settimeout to implement the request.
function Createxmlhttprequest () {var request = false; if (window. XMLHttpRequest) {request = new XMLHttpRequest (); if (request.overridemimetype) {request.overridemimetype (' text/xml '); }} else if (window. ActiveXObject) {var versions = [' Microsoft.XMLHTTP ', ' MSXML. XMLHTTP ', ' microsoft.xmlhttp ', ' msxml2.xmlhttp.7.0 ', ' msxml2.xmlhttp.6.0 ', ' msxml2.xmlhttp.5.0 ', ' msxml2.xmlhttp.4.0 ', ' MSXML2. xmlhttp.3.0 ', ' MSXML2. XMLHTTP ']; for (var i=0; i<versions.length; i++) {try {request = new ActiveXObject (versions[i]); if (request) {return request; }} catch (e) {}}} return request; function Ajax (Xmlhttp,_method, _url, _param, _callback) {if (typeof xmlhttp = = ' undefined ') return; Xmlhttp.onreadystatechange = function () {if (xmlhttp.readystate==4 && xmlhttp.status==200) {_c Allback (XMLHTTP); }} XMLHTtp.open (_method, _url, true); if (_method = = "POST") {Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); Xmlhttp.setrequestheader ("Content-length", _param.length); Xmlhttp.send (_param); } else {xmlhttp.send (null); }}
//Examples of UsevarXMLHTTP =createxmlhttprequest ();varT1;//used for timeout processingfunctionAdduserok (Request) {alert (request.responsetext); if(t1) cleartimeout (t1);}functionConnecttofail () {if(XMLHTTP) xmlhttp.abort (); Alert (' Time Out ');}if(XMLHTTP) {Ajax (XMLHTTP,"POST", "http://10.1.2.187/adduser.cgi", "ACT=DO&USER=ABC", Adduserok); T1= SetTimeout (connecttofail,30000);}Else{alert ("Init XMLHttpRequest Fail");}
Using SETTIMEOUTC to process JavaScript Ajax request Timeouts