即時通訊使用類似的腳本描述在這裏:long-polling info from mysql not working 在我的網站,它的工作,但是,當我刷新頁面或點擊不同的鏈接,我得到一個錯誤提醒+網站開始嚴重滯後,有人能告訴我這是什麼原因?ajax與mysql的長輪詢
我的代碼:
$oldIDq = mysql_query("SELECT * FROM messages ORDER BY id DESC LIMIT 1");
while($oldrow = mysql_fetch_array($oldIDq)){
$oldID = $oldrow['id'];
}
$func = '
var oldID = '.$oldID.';
function wait() {
$.ajax({
type: "GET",
url: "../scripts/msg_scripts/msg.php?oldid=" + oldID,
async: true,
cache: false,
success: function (data){
var json = eval(\'(\' + data + \')\');
if (json[\'msg_content\'] != "") {
alert("new meassage added");
}
oldID = json[\'oldID\'];
setTimeout(\'wait()\',1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("error: " + textStatus + "(" + errorThrown + ")");
setTimeout(\'wait()\',15000);
}
});
}
$(document).ready(function(){
wait();
});
';
服務器:
<?php
session_start();
$connect = mysql_connect ("localhost", "root", "")
or die ("couldnt connect");
mysql_select_db ("***") or die ("not found"); //if db was not found die
mysql_query("SET NAMES 'utf8'");
$oldID = $_GET['oldid'];
$result = mysql_query("SELECT id FROM messages ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$last_msg_id = $row['id'];
}
while($last_msg_id <= $oldID)
{
usleep(1000);
clearstatcache();
$result = mysql_query("SELECT id FROM messages ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$last_msg_id = $row['id'];
}
}
$response = array();
$response['msg'] = 'new';
$response['oldID'] = $last_msg_id;
echo json_encode($response);
?>
@ moonwave99 - 我同意。 –
aaaargh!幫幫我! eval ===邪惡使用JSON.parse(jsonString)instaid!而且你甚至不需要解析!如果你添加'dataType:'json''參數,jquery可以爲你做到這一點! – VDP
謝謝你,我會試試:) – durian