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

yipeiwu_com6年前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学习中常见的各类问题,约有两千多行代码,都是非常实用的技巧。分享给大家供大家参考。具体如下: //语法错误(syntax error)在语法分析阶段,源代码并未被执行...

提高define性能的php扩展hidef的安装和使用

提高define性能的php扩展hidef的安装和使用

官网:http://pecl.php.net/package/hidef简介:  Allow definition of user defined constants in simple...

PHP GD库添加freetype拓展的方法

背景:业务需求要用到 imagefttext 函数,发现GD库一开始安装时没有添加 FreeType linux版本 centos 6.6 安装流程(由于服务器为分布式内网服务器,无法使...

windows7下安装php的imagick和imagemagick扩展教程

最近的PHP项目中,需要用到切图和缩图的效果,在linux测试服务器上很轻松的就安装好php imagick扩展。但是在本地windows开发环境,安装过程遇到好多问题,在此与大家分享。...

php断点续传之如何分割合并文件

复制代码 代码如下: <?php ini_set("memory_limit", "50M");//必须的,根据你环境的实际情况尽量大,防止报错 ini_set("max_exec...