【发布时间】:2012-02-03 01:32:57
【问题描述】:
我正在创建一个通知系统,该系统会立即检查在线用户是否有任何新通知。
到目前为止,这是我的脚本:
//...include(myscripts.php)...
function notificationsCount($id)
{
if(is_numeric($id) && !empty($id) && $id>0) return mysql_result(mysql_query("SELECT COUNT(*) FROM notifications WHERE unRead='1' AND userID = '$id'"),0);
}
if($_GET['getNotificiationCount'] && $_GET[userID])
{
$current = notificationsCount($_SESSION['userID']);
$count = 0;
while($count<20 && !connection_aborted()){
$c = notificationsCount($_SESSION['userID']);
if($c!=$current && $c!=0)
exit($c);
$count++;
sleep(1);
}
exit("0");
}
客户端:
var checkNotify;
$(window).unload(function () { checkNotify.abort(); } );
//Nav Notifications
function checkNotifications()
{
checkNotify = $.ajax({
url: "/notifications.php?getNotificiationCount=true&userID=<?=$_SESSION[userID]?>",
timeout: "30000",
cache: false,
success : function(data, textStatus, XMLHttpRequest) {
if(data!=0) {
$("#nav_notification_bubble").removeClass("displayoff");
$("#notification_count").html(data); }
checkNotifications();
},
error: function() {}
});
}
checkNotifications();
这可行,但是如果我离开页面,网络服务器将不会响应(在我的客户端),直到“notifications.php”脚本完成。
如果客户端离开页面,我该怎么做才能杀死脚本?
我的 Web 服务器是否打开了 Apache Gzip - 会等待缓冲区完成吗?
【问题讨论】:
-
JavaScript 需要异步编写。
checkNotify是试图被覆盖而不是创建新实例的单个 var。
标签: php javascript jquery apache long-polling