由于您最初的问题是这两种技术之间的区别是什么,所以我将从以下开始:
AJAX 轮询
使用 AJAX 轮询更新页面意味着您以定义的时间间隔向服务器发送请求,如下所示:
客户端向服务器发送请求,服务器立即响应。
一个简单的例子(使用 jQuery)如下所示:
setInterval(function(){
$('#myCurrentMoney').load('getCurrentMoney.php');
}, 30000);
这样做的问题是,这将导致很多无用的请求,因为每个请求不会总是有新的东西。
AJAX 长轮询
使用 AJAX 长轮询意味着客户端向服务器发送请求,服务器在响应之前等待新数据可用。这看起来像这样:
客户端发送请求,服务器“不定期”响应。一旦服务器响应,客户端就会向服务器发送一个新的请求。
客户端如下所示:
refresh = function() {
$('#myCurrentMoney').load('getCurrentMoney.php',function(){
refresh();
});
}
$(function(){
refresh();
});
这只是将getCurrentMoney.php 的输出加载到当前的money 元素中,一旦有回调,就开始一个新的请求。
在服务器端,您通常使用循环。为了解决您的问题,服务器将如何知道哪些是新发布:要么将最新的时间戳传递给客户端可用发布到服务器,要么使用“长轮询开始”的时间作为指标:
<?
$time = time();
while ($newestPost <= $time) {
// note that this will not count as execution time on linux and you won't run into the 30 seconds timeout - if you wan't to be save you can use a for loop instead of the while
sleep(10000);
// getLatestPostTimestamp() should do a SELECT in your DB and get the timestamp of the latest post
$newestPost = getLatestPostTimestamp();
}
// output whatever you wan't to give back to the client
echo "There are new posts available";
在这里我们不会有“无用”的请求。