javascript - How to detect timeout on an AJAX (XmlHttpRequest) call in the browser? -


i'm looking on web, documentation hard come by. know basic ajax call using browser's built-in xmlhttprequest object (assume modern browser here):

    var xmlhttp = new xmlhttprequest();  // assumes native object      xmlhttp.open("get", "http://www.example.com", false);      xmlhttp.send("");      var statuscode = xmlhttp.status;     // process it, , i'd love know if request timed out 

so, there way can detect ajax call timed out inspecting xmlhttprequest object in browser? advised window.settimeout(function() { xmlhttp.abort() }, 30000);?

thanks!

-mike

update: here's an example of how can handle timeout:

var xmlhttp = new xmlhttprequest(); xmlhttp.open("get", "http://www.example.com", true);  xmlhttp.onreadystatechange=function(){    if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {       cleartimeout(xmlhttptimeout);        alert(xmlhttp.responsetext);    } } // we're ready handle response, can make request xmlhttp.send(""); // timeout abort in 5 seconds var xmlhttptimeout=settimeout(ajaxtimeout,5000); function ajaxtimeout(){    xmlhttp.abort();    alert("request timed out"); } 

in ie8, can add timeout event handler xmlhttprequest object.

var xmlhttp = new xmlhttprequest(); xmlhttp.ontimeout = function(){   alert("request timed out"); } 

i recommend against making synchronous calls code implies , recommend using javascript framework this. jquery popular one. makes code more efficient, easier maintain , cross-browser compatible.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -