判断用户是否在线的代码-javascript技巧

时间:2016-04-09
考虑两种情况:
(1)用户关闭浏览器或重定向到其他网页
代码如下:

<script type=text/javascript>
function exit_init() {
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){ //
}
else{
alert("there was a problem accessing the server:"+xmlhttp.status);
}
}
}
//定义windows 的onbeforeunload 事件,当用户非正常退出即浏览器非正常关闭时,对用户登录状态进行处理
window.onbeforeunload=function () {
//if(event.clientY<0||event.altKey) {
exit_request = false;
//创建请求对象
if (window.XMLHttpRequest) {
exit_request = new XMLHttpRequest();
if (exit_request.overrideMimeType){
exit_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) {
try{
exit_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
exit_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!exit_request) {
alert("Your brower is not compatible the current opration.Please use the IE 5.0! ");
return false;
}
var url='null.php?userid='+document.getElementById("userid").value;
//定义页面调用的方法exit_init,不是exit_init();没有();
exit_request.onreadystatechange = exit_init;
exit_request.open('GET', url, true);
//禁止IE 缓存
exit_request.setRequestHeader("If-Modified-Since","0");
//发送数据
exit_request.send(null);
}
/

相关文章