日期:2014-05-16 浏览次数:20718 次
function getXMLHttpRequest(){ var client = getXMLHttpRequestFromIE(); if(client == null){ client = new XMLHttpRequest(); } return client; } function getXMLHttpRequestFromIE(){ var namePrefixes = ["Msxml3","Msxml2","Msxml","Microsoft"]; for(var i = 0; i < namePrefixes.length; i++){ try{ var name = namePrefixes[i] + ".XMLHTTP"; return new ActiveXObject(name); }catch(e){ } } return null; } var client = null; //是否可以访问 var isRun = false; //返回值 var stateString=""; //请求url的网站 function connUrl(url){ client = getXMLHttpRequest(); var actionURL = convertURL(url); try{ client.open("GET", actionURL, true); client.onreadystatechange = callBack; client.send(null); }catch(e){} finally{ } } function callBack(){ if(client.readyState == 4){ stateString = client.responseText; if(stateString && client.status==200) isRun = true; } } //是否可达 function isReach(url){ connUrl(url); return isRun; } //给url地址增加时间戳,骗过浏览器,不读取缓存 function convertURL(url) { //获取时间戳 var timstamp = (new Date()).valueOf(); //将时间戳信息拼接到url上 if (url.indexOf("?") >= 0) { url = url + "&t=" + timstamp; } else { url = url + "?t=" + timstamp; } return url; } //因为是异步,先调用,此时isRun的值是false isReach("http://www.baidu.com"); //3秒钟后判断isRun的值,如果为false认为网站不可达,类似超时时间 setTimeout(function(){ //alert(stateString); //alert(isRun); if(isRun==true){ document.getElementById("ceshi").innerText = "网站是通的!"; }else{ document.getElementById("ceshi").innerText = "网站不通!"; } },3000);
?
<div id="ceshi"></div>
?