js浏览器端判断当期是否在线
作者:zccst 纯浏览器端解决办法就是轮询,img轮询和ajax 批注:img轮询要加时间戳,ajax轮询要避免跨域。 [code="js"] var img = new Image(); img.id = "test_is_online"; img.onload = function(){ document.body.removeChild(document.getElementById("test_is_online")); alert("在线"); }; img.onerror = function(){ document.body.removeChild(document.getElementById("test_is_online")); alert("断网了!"); }; img.src = "http://www.baidu.com/img/baidu_jgylogo3.gif?v="+(+new Date()); img.style.display = "none"; document.body.appendChild(img); //自己写的,还不完善 $('
').load(function(){ this.isOnline = true; alert("load"+this.isOnline); }).error(function(){ this.isOnline = false; alert("error"+this.isOnline); }); [/code] [code="js"] //创建xmlHttp对象 var xmlHttp = null; function createXMLRequest( ){ var msxmlhttp = new Array( 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'); for(var i = 0; i < msxmlhttp .length; i++) { try { if(xmlHttp = new ActiveXObject(msxmlhttp[i] )) break; } catch (e) { xmlHttp = null; } } if(!xmlHttp && typeof XMLHttpRequest != "undefined") xmlHttp = new XMLHttpRequest(); } function getHtml(){ createXMLRequest( ); //状态调用函数 xmlHttp.onreadystatechange = function(){ if ( xmlHttp.readyState == 4 ){ if (xmlHttp.status == 200){ //状态成功执行,有网络 reflesh(); alert("有网"); }else{ //没有网络跳转到a.html页面 document.all.cma.src="a.html"; alert("没网"); } } } //发送请求 xmlHttp.open( "get","http://m.weather.com.cn/m/pn2/weather.htm" ,true); xmlHttp.send( null ); } function reflesh(){ //var city = System.Gadget.Settings.read("city"); var city = "2"; if (city > 100000000) { document.all.cma.src="http://m.weather.com.cn/m/pn2/weather.htm?id="+city+"T"; } else { document.all.cma.src="http://m.weather.com.cn/m/pn2/weather.htm"; } } getHtml(); //跨域 var xmlHttplink; function createXMLLinkHttpRequest() { if (window.ActiveXObject) { xmlHttplink = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xmlHttplink = new XMLHttpRequest(); } } function doRequest() { createXMLLinkHttpRequest(); xmlHttplink.onreadystatechange = handleChange; xmlHttplink.open("HEAD", "http://bbs.csdn.net/topics/320003524&date=" + new Date().getTime(), true); xmlHttplink.send(null); } function handleChange() { if(xmlHttplink.readyState == 4) { if(xmlHttplink.status == 200){ document.getElementById("netlink").value="连接"; alert("在线") }else{ document.getElementById("netlink").value="断开"; alert("连接断开"); } setTimeout("doRequest()", 1000); } } doRequest(); [/code]