javascript - Detect ajax request no connection status and state -
i'm working pure javascript (no jquery , no others...) , i'm writing code make ajax request. noticed when internet connection fails, on chrome, firefox , ie values in xmlhttp.onreadystatechange:
xmlhttp.readystate=4 xmlhttp.status=0
since handle network connection problems way it?
xmlhttp.onreadystatechange=function(){ if(xmlhttp.readystate==4 && xmlhttp.status==0){//no internet connection //code handle network error } }
this code seems work me, haven't seen documentation abuot this, nowhere! think solid solution?
you can use online/offline events:
window.addeventlistener('load', function() { var status = document.getelementbyid("status"); function updateonlinestatus(event) { var condition = navigator.online ? "online" : "offline"; status.classname = condition; status.innerhtml = condition.touppercase(); log.insertadjacenthtml("beforeend", "event: " + event.type + "; status: " + condition); } window.addeventlistener('online', updateonlinestatus); window.addeventlistener('offline', updateonlinestatus); });
#status { position : fixed; width: 100%; font : bold 1em sans-serif; color: #fff: padding : 0.5em } #log { padding: 2.5em 0.5em 0.5em; font: 1em sans-serif; } .online { background: green; } .offline { background: red; }
<div id="status"></div> <div id="log"></div> <p>this test</p>
Comments
Post a Comment