当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP+Ajax实时自动检测是否联网的方法

PHP+Ajax实时自动检测是否联网的方法

2018年05月15日  | 移动技术网IT编程  | 我要评论

本文实例讲述了php+ajax实时自动检测是否联网的方法。分享给大家供大家参考。具体实现方法如下:

html部分代码:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" 
"http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php+ajax实时自动检测是否联网</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script type="text/javascript">
<!--
var xmlhttp;
function createxmlhttprequest(){
  if(window.activexobject){
    xmlhttp = new activexobject("microsoft.xmlhttp");
  }
  else if(window.xmlhttprequest){
    xmlhttp = new xmlhttprequest();
  }
}
function start(){
  createxmlhttprequest();
  var url="getnetlink";
  xmlhttp.open("get",url,true);
  xmlhttp.onreadystatechange = callback;
  xmlhttp.send(null);
}
function callback(){
  if(xmlhttp.readystate == 4){
    if(xmlhttp.status == 200){
      document.getelementbyid("shownetlink").innerhtml = xmlhttp.responsetext;
      settimeout("start()",8000);
    }
  }
}
// -->
</script>
</head>
<body onload="start();">
<h1>php+ajax实时自动检测是否联网</h1>
<p>当前网络状态:<span id="shownetlink"></span></p>
</body>
</html>

php部分代码:

public function getnetlink(){ 
  header("cache-control:no-cache,must-revalidate"); 
  header("content-type:text/html;charset=utf-8"); 
  $file=fopen("http://www.baidu.com/", "r"); 
  if (!$file){ 
   $shownetlink = "<font color=\"red\">网络连接失败</font>"; 
  }else{ 
   $shownetlink = "<font color=\"#06c\">网络连接正常</font>"; 
  } 
  echo $shownetlink; 
}

希望本文所述对大家的php程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网