Ajax+php长轮询出错



我正在尝试执行ajax php轮询功能,它似乎运行良好,但我不明白出了什么问题,或者我误解了什么?

让我们看看我的代码:

*在index.php中*

  $tst = $conn->prepare('SELECT dtimestamp FROM inbx where recipient=:recipient  ORDER BY dtimestamp DESC LIMIT 1');
  $tst->bindParam(':recipient', $row['user_id']);
  $tst->execute();
  $rk= $tst->fetch();
<body onload="chkinbx(<?php echo $row['user_id']?>, <?php echo $rk['dtimestamp'] ?>);">

在Javascript中

function chkinbx (user_id, cur_time) {
var old_timestamp=0;
var url="function.php?user_id="+user_id+"&cur_time="+cur_time;
var params="user_id="+encodeURIComponent(user_id)+"&cur_time="+encodeURIComponent(cur_time);

xmlHttp=GetXmlHttpObject()
xmlHttp.onreadystatechange=function () {
 if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
var result=xmlHttp.responseText;
var res=JSON.parse(result);

if(res[2]==old_timestamp || cur_time==res[2]){
////  do nothing
}else{
    document.getElementById(bb).innerHTML="<a class='topNav' href='inbox.php'><span class='countmsg'>"+res[1]+"</span></a>";

}
setTimeout(function() {
chkinbx (res[3], res[4], cur_time);  // div   user_id   curtime
}, 1000); //8 seconds
 }
}

在function.php中

$params=$_POST['params'];
$user_id=$_POST['user_id']; 
$cur_time=$_POST['cur_time'];
  $stmt = $conn->prepare('SELECT dtimestamp FROM inbx where recipient=:recipient AND inbxicn_is_click=:inbxicn_is_click  ORDER BY database_timestamp DESC' );
  $stmt->execute(array(':recipient'=>$user_id,':inbxicn_is_click'=>'N'));
  $r=$stmt->fetch();
while ($r['dtimestamp'] <= $cur_time) {
  sleep(10);
  clearstatcache();
 }
     $phpArray = array("ok",$stmt->rowCount(), $r['database_timestamp'], $user_id);
     echo json_encode($phpArray);

除非我更改为($r['dtimestamp']>$cur_time),否则它不会工作*我想知道为什么*

因为逻辑是$cur_time(javascript中的post是index.php中的原始时间戳。$r['dtimestamp']是数据库中的当前时间戳。这与逻辑相反。

因为在$r['dtimestamp']>$cur_time之前,你已经告诉它休眠10并执行clearstatcache(),

while ($r['dtimestamp'] <= $cur_time) {
  sleep(10);
  clearstatcache();
 }

只有$r['dtimestamp']>$cur_time一次,它才会退出while循环,如果$r[[dtimestamp']<开始的cur_time永远不会突然得到>,除非clearstatcache中的某个东西正在更改$cur_time

相关内容

  • 没有找到相关文章

最新更新