是的,你描述它的方式是长轮询方法是如何工作的。 您的示例代码有点模糊,所以我想补充一点,您应该在while
循环内执行sleep()
一小段时间,并且每次比较last_checked
时间(存储在服务器端)和current
时间(这是从客户端发送的内容)。
事情是这样的:
$current = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$last_checked = getLastCheckedTime(); //returns the last time db accessed
while($last_checked <= $current) {
usleep(100000);
$last_checked = getLastCheckedTime();
}
$response = array();
$response['latestData'] = getLatestData() //fetches all the data you want based on time
$response['timestamp'] = $last_checked;
echo json_encode($response);
而在您的客户端JS你有这样的:
function longPolling(){
$.ajax({
type : 'Get',
url : 'data.php?timestamp=' + timestamp,
async : true,
cache : false,
success : function(data) {
var jsonData = eval('(' + data + ')');
//do something with the data, eg display them
timestamp = jsonData['timestamp'];
setTimeout('longPolling()', 1000);
},
error : function(XMLHttpRequest, textstatus, error) {
alert(error);
setTimeout('longPolling()', 15000);
}
});
}
这是一个很好的问题,我正要问同样的问题。 – samayo