当前位置: 代码迷 >> JavaScript >> 来,求JS一个函数的写法
  详细解决方案

来,求JS一个函数的写法

热度:377   发布时间:2012-02-15 12:09:43.0
高手请进来,求JS一个函数的写法
要求每隔五秒钟,检查一次是否连通互联网,是的话,返回当前的IP(我用的是ADSL直接连通外网的),没有联网的话返回“没有联网”的字符串.谢谢。


------解决方案--------------------
<script type= "text/javascript ">
window.onload=function(){
checknet();
setInterval(checknet,5*1000)
}

var tStart=null;

function checknet(){
var url= "http://www.ajiang.net/aspcheck.asp ";
var conn=new XHConn();
tStart=new Date();
conn.connect(url, "GET ", "T=E&R= "+Math.random(),callback);
}

function callback(response){
var text=response.responseText;
var tEnd=new Date();
var speed=(text.length/(tEnd-tStart)).toFixed(3);
if (text && text.indexOf( "http://www.ajiang.net/products/aspcheck/ ")!=-1){
var arr=text.match(/> REMOTE_ADDR <\/td> <td[^> ]*> ([^ <]+) <\/td> <\/tr> /);
if (arr && arr.length> =2 && /(\d+)\.(\d+)\.(\d+)\.(\d+)/.test(arr[1])){
addLog(arr[1]+ "\t网速:\t "+speed+ " k/s ");
}else{
addLog( "没有联网 ");
}

}else{
addLog( "没有联网 ");
}
}

function addLog(msg){
var output=document.getElementById( "output ");
var now=new Date().toLocaleTimeString();
output.value=output.value+now+ "\tIP: "+msg+ "\r\n "
}


function XHConn(){
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject( "Msxml2.XMLHTTP "); }
catch (e) { try { xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP "); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) return null;
this.connect = function(sURL, sMethod, sVars, fnDone){
if (!xmlhttp) return false;
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET "){
xmlhttp.open(sMethod, sURL+ "? "+sVars, true);
sVars = " ";
}else{
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader( "Method ", "POST "+sURL+ " HTTP/1.1 ");
xmlhttp.setRequestHeader( "Content-Type ", "application/x-www-form-urlencoded ");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && !bComplete){
bComplete = true;
fnDone(xmlhttp);
}};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}

</script>
<textarea id= "output " style= "margin:50px;width:70%;height:500px;overflow:auto " readonly> </textarea>
  相关解决方案