本节主要内容:
PHP+Ajax结合,实现实时自动检测是否联网。
1,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实时自动检测是否联网-www.jbxue.com</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 οnlοad="start();">
<h1>PHP+Ajax实时自动检测是否联网</h1>
<p>当前网络状态:<span id="shownetlink"></span></p>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PHP+Ajax实时自动检测是否联网-www.jbxue.com</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 οnlοad="start();">
<h1>PHP+Ajax实时自动检测是否联网</h1>
<p>当前网络状态:<span id="shownetlink"></span></p>
</body>
</html>
2,php代码
复制代码 代码示例:
<?php
//检测 网络连接,是否已联网
public function getNetLink(){
header("cache-control:no-cache,must-revalidate");
header("Content-Type:text/html;charset=utf-8");
$file=fopen("http://www.jbxue.com/", "r");
if (!$file){
$shownetlink = "<font color=\"red\">网络连接失败</font>";
}else{
$shownetlink = "<font color=\"#06C\">网络连接正常</font>";
}
echo $shownetlink;
}
//检测 网络连接,是否已联网
public function getNetLink(){
header("cache-control:no-cache,must-revalidate");
header("Content-Type:text/html;charset=utf-8");
$file=fopen("http://www.jbxue.com/", "r");
if (!$file){
$shownetlink = "<font color=\"red\">网络连接失败</font>";
}else{
$shownetlink = "<font color=\"#06C\">网络连接正常</font>";
}
echo $shownetlink;
}