今天碰到了一个PHP轮询的代码,主要是借助js的setInterval()函数实现定时轮询的。具体代码如下。
js代码
function polling(){
//执行轮询代码
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHTTP=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.status==200 && xmlHttp.readyState==4){
result=xmlHttp.responseText;
if(result=="true"){
window.location.href="welcom.php";
}
}
}
xmlHttp.open('GET',"polling.php?randnumber=123456",true);
xmlHttp.send();
}
PHP代码
require 'mysql_connect.php';
$randnumber=$_GET['randnumber'];
$result=mysql_query("select * from login_record where randnumber='$randnumber'");
$row=mysql_fetch_array($result);
if($row['username']!=""){
echo "true";
}else{
echo "false";
}
?>