【发布时间】:2014-05-23 05:14:26
【问题描述】:
我的框架是 PHP Laravel 4。我正在使用长轮询技术来刷新我的 HTML 页面上的列表。在同一页面中,我有一个自动提交下拉列表。当用户选择一个选项时,它只是自动提交以重置会话值。重置会话页面后会刷新。但是这里有一个错误。当我开始轮询会话时没有正确更新。有时它会更新,但大多数时候不会。
这就是我在 AJAX 长轮询 PHP 服务器端函数中尝试做的事情
public function getNewAppt() {
//Session is open now. Connection to the server is opened. Session file is locked
//Close the session
if (session_status() != PHP_SESSION_NONE) {
session_write_close();//close
}
$today_appt_count = 0;
$result = Appointment::with(array('user' => function($query) {
$query->where('branch_id', Session::get('branch_id'));
}))->where('start', 'LIKE', date('Y-m-d') . ' %')->get();
foreach ($result as $appt) {
if ($appt->user != null) {
$today_appt_count++;
}
}
return $today_appt_count;
}
当用户更改下拉菜单时,首先我停止这样的长轮询功能,
console.log('Long Polling has Stopped');
ajaxLongPoll.abort();//Stop the long polling function
然后我会自动向这个 php 函数提交一个 html 表单。
public function postChangeBranch() {
//Session is closed now, so start the session
if (session_status() == PHP_SESSION_NONE) {
session_start(); //start session again
}
Session::forget('branch_id');
Session::put('branch_id', Input::get('branch_id'));
return Redirect::to('calendar');
}
这是长轮询ajax函数
var poll = function() {
ajaxLongPoll = $.ajax({
type: 'GET',
url: 'calendar/new-appt',
dataType: 'html',
success: function(data) {
//update stuff
requestCount++;
console.log(requestCount);//number of times this function runs...
console.log(data);//this will just print a live count from DB
},
error: function(data) {
console.log(data);
},
complete: function() {
poll();// recall this function after 30 sec
},
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout: 30000 /* Timeout in ms */
});
}//polling end
你能告诉我我在这里做错了什么吗?非常感谢!
【问题讨论】:
-
在成功函数中添加
console.log(data),看看控制台会发生什么。它不是您设置的长时间轮询,所以我怀疑它触发太多请求的速度太快,并且成功功能正在重新启动,就像它每次完成一样。也许您对timeout选项感到困惑。所做的只是在取消请求之前在请求上设置一个 30 秒的计时器,它不会强制 jquery 在每个请求之间等待 30 秒。 -
console.log(data) 只会从数据库中打印实时计数。它只是继续打印价值。这个功能看起来工作正常。我在控制台中看不到任何错误。我认为会话问题出在 PHP 代码中。 :(
-
打印速度快吗?
标签: php ajax session laravel long-polling