欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP+Ajax 检测网络是否正常实例详解

程序员文章站 2024-04-01 19:25:58
本文实例讲述了php+ajax实时自动检测是否联网的方法。分享给大家供大家参考。具体实现方法如下: html部分代码:

本文实例讲述了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; 
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!