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

yipeiwu_com5年前PHP代码库

本文实例讲述了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安装php_rar扩展实现rar文件读取和解压的方法

本文实例讲述了php安装php_rar扩展实现rar文件读取和解压的方法。分享给大家供大家参考,具体如下: PHP Rar Archiving 模块 (php_rar) 是一个读取和解压...

PHP基于DOM创建xml文档的方法示例

本文实例讲述了PHP基于DOM创建xml文档的方法。分享给大家供大家参考,具体如下: DOM创建xml文档 用dom创建如下文档: <booklist>   <bo...

php常用正则函数实例小结

本文实例总结了php常用正则函数。分享给大家供大家参考,具体如下: 1. mixed preg_replace(mixed pattern, mixed  replacemen...

PHP连接SQLSERVER 注意事项(附dll文件下载)

环境: - Apache 2.2.6 - PHP 5.2.5 - SQL Server 2005 - Windows XP SP2 步骤: 1. 首先按通常做法配置好PHP5连接MS S...

PHP实现的一致性HASH算法示例

本文实例讲述了PHP实现的一致性HASH算法。分享给大家供大家参考,具体如下: <?php // +----------------------------------...