我想實現我的intranetwork長輪詢系統,大多數用戶使用IE瀏覽器和一些移動使用過,這就是爲什麼我試圖用長輪詢而不是用websocket來做到這一點。PHP + jQuery的 - 長輪詢與數據庫中的數據不工作(不破環)
我跟着這個視頻http://www.screenr.com/SNH,我編輯了一些代碼來處理我的數據庫。 (火鳥)
這一切似乎都沒問題,但它並沒有打破循環。也許這是一個孩子的錯誤,但我看不到它,這就是爲什麼我需要你的幫助!
下面的代碼:
的jQuery + Ajax的:
var timestamp = null;
function waitForMsg(){
$.ajax({
type: "GET",
url: "getData.php?timestamp=" + timestamp,
async: true,
cache: false,
success: function(data){
alert('It Works');
var json = eval('(' + data + ')');
timestamp = json['timestamp'];
setTimeout('waitForMsg()',15000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("A - " + XMLHttpRequest + " - error: " + textStatus + " (" + errorThrown + ")");
setTimeout('waitForMsg()',15000);
}
});
}
$(document).ready(function(){
waitForMsg();
});
</script>
訪問getdata.php( 'DATAHORA' 是時間戳字段)
<?php
set_time_limit(0);
@ini_set("memory_limit",'64M');
require_once('../classes/conexao.php');
$banco = Conexao :: getConexao();
$sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATAHORA']);
else
$currentmodif = 0;
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
while($currentmodif <= $lastmodif){
usleep(10000);
$sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATAHORA']);
else
$currentmodif = 0;
}
$response = array();
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
當我插入,更新,或者刪除一些數據,時間戳字段用當前時間戳更新。 我可以看到頁面進入循環,但我不知道爲什麼它永遠不會結束。
我做錯了什麼?
謝謝
'eval()'?爲什麼評價JSON,當jQuery已經有完美的內置JSON處理?還有...爲什麼循環要退出?在你的'success'和'error'代碼路徑中,你無條件地在每次迭代時重新安排'waitForMsg()' - 循環無法退出。如果你想讓它退出,你必須放棄它。 –
@MarcB我只是跟着視頻教程,這就是爲什麼'eval()'和其他。如果我嘗試相同的代碼,但使用文件和'filetime',它就像一個魅力。在此代碼中,如果數據庫中添加了新信息,它應該退出循環並傳遞json值,然後返回到帶有循環的頁面。 – void