js浏览器端判断当期是否在线

作者:zccst

纯浏览器端解决办法就是轮询,img轮询和ajax

批注:img轮询要加时间戳,ajax轮询要避免跨域。



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);


//自己写的,还不完善
$('<img src="http://www.baidu.com/img/baidu_jgylogo3.gif" />').load(function(){
this.isOnline = true;
alert("load"+this.isOnline);
}).error(function(){
this.isOnline = false;
alert("error"+this.isOnline);
});


//创建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();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值