本文實例講述了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; }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!