【发布时间】:2011-10-17 17:08:50
【问题描述】:
我的页面上有一个长轮询请求。服务器端的脚本设置为20秒后超时。
因此,当长轮询处于“空闲”状态,并且用户按下另一个按钮时,新请求的发送将延迟到前一个脚本超时。
我看不出 jQuery 端的代码有什么问题。为什么 onclick-event 会延迟?
function poll()
{
$.ajax({
url: "/xhr/poll/1",
data: {
user_id: app.user.id
},
type: "POST",
dataType: "JSON",
success: pollComplete,
error: function(response) {
console.log(response);
}
});
}
function pollComplete()
{
poll();
}
function joinRoom(user_id)
{
$.ajax({
url: "/xhr/room/join",
dataType: "JSON",
type: "POST",
data: {
user_id: app.user.id,
room_id: room.id
}
});
}
<button id="join" onclick="javascript:joinRoom(2);">Join</button>
############ PHP Controller on /xhr/poll
$time = time();
while ((time() - $time) < 20)
{
$updates = $db->getNewStuff();
foreach ($updates->getResult() as $update)
$response[] = $update->getResponse();
if (!empty($response))
return $response;
else
usleep(1 * 1000000);
return 'no-updates';
}
“睡眠”会是问题吗?
【问题讨论】:
-
本地主机也有问题吗??
-
任一 AJAX 调用的 PHP 代码是否使用会话?
标签: jquery ajax xmlhttprequest long-polling