长轮询脚本会停止所有其他脚本

时间:2013-12-10 12:30:40

标签: javascript php jquery ajax

我使用以下脚本开始使用php文件进行长轮询..它检查是否有任何结果更新并发送响应..

由于某种原因,当插入这个javascript时,所有其他脚本都会挂起一个关于fire bug的长轮询

function waitForMsg(){
$.ajax({
    type: "GET",
    url: "auth/classes/getdata.php",
    async: true,
    cache: false,

    success: function(data){

    console.log(data)

    setTimeout("waitForMsg()",1000);
    },
    error: function(XMLHttpRequest,textStatus,errorThrown) {
//   alert("error: "+textStatus + "  "+ errorThrown  );
    setTimeout("waitForMsg()",15000);
    }
  });
}


$(document).ready(
 function() 
 {  

  waitForMsg();
 });

这是php文件getdata.php

require_once($_SERVER['DOCUMENT_ROOT'].'/auth/config/db.php');
 $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

$user_id = $_SESSION['user_id']; 
$lastmodif = time();
$update = 1;
while ($update <= $lastmodif) {
usleep(10000);
clearstatcache();
 $sql = "select ua.user_id as member,ua.post_id,pa.user_id,pa.type,pa.time,CONCAT(u.first_name,' ',u.last_name) as
 name,u.thumbnail from user_activity ua right join post_activity pa on 
 ua.post_id=pa.post_id right join users u on pa.user_id=u.user_id where
  ua.user_id=".$user_id." and pa.time > FROM_UNIXTIME('".$lastmodif."')";
  $result = $conn->query($sql) or die(mysqli_error());
 if ($conn->affected_rows > 0) {
$update=$lastmodif;
$response = array();
$response['msg'] ='update';
echo json_encode($response);

 }
}

2 个答案:

答案 0 :(得分:1)

非常确定你的问题是

usleep(10000);

这将有效地停止执行以及您尝试使用setTimeout("waitForMsg()",1000);启动的ajax循环 - 执行逻辑的usleep块。

答案 1 :(得分:-1)

<?

 if(!define("_IS_GET"))
exit("Use another form to get get awww");
else
{
ignore_user_abort(TRUE);
set_time_limit(0); // adjust this to trap long time load
//...your lame process here

//sample you wanna dogetdata.php

$prId = shell_exec("nohup -f php '/path/to/your/getdata.php' /dev/null 2&<1 & $!",$display);

while(exec("$prId -s"))
echo $display."\n<BR>";

// note killing your jobs can be done using prId so its your initiative to store it and keep it ?
}
?>