我要从我的数据库中编写一个长轮询查询 - 目前正在使用mysqli。我成功调用数据并返回我的javascript代码,但是,现在是技巧部分,2分钟后,我收到此错误:" Uncaught SyntaxError:意外的输入结束"。
我用Google搜索并阅读了几页(我估计超过30页),但我无法解决这个问题...... 每个人都说很可能是我忘了关闭一些括号...但我猜不是..
另一方面,我更喜欢使用json.parse()
而不是eval()
..而且它们都不起作用......
感谢关注 Ps。:我不是英国本土的speacker,抱歉任何拼写错误;)
var old_msg_id = "<?php echo $old_msg_id; ?>";
function waitForMsg() {
$.ajax({
type: "GET",
url: "poll.php?old_msg_id=" + old_msg_id,
async: true,
cache: false,
//dataType : 'json',
success: function (dataRespond) {
//var jsonAnswer = eval("(" + dataRespond + ")");
var jsonAnswer = JSON.parse(dataRespond);
if (jsonAnswer.msg !== "") {
alert("New msg added to base!");
console.log(jsonAnswer.msg);
};
old_msg_id = jsonAnswer.old_msg_id;
setTimeout('waitForMsg()', 1000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Deu merda!: Error: " + textStatus + " (" + errorThrown + ")");
setTimeout('waitForMsg()', 15000);
}
});
}
$(document).ready(function () {
waitForMsg();
});
error_reporting(0);
$conn = mysql_connect("localhost", "root", "");
mysql_select_db('padova', $conn) or die('Could not select database.');
$result = mysql_query("SELECT id FROM test ORDER BY id DESC LIMIT 1");
if($result === FALSE) {
die(mysql_error());
}
$old_msg_id = $_GET['old_msg_id'];
$result = mysql_query("SELECT id, text FROM test ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$last_msg_id = $row['id'];
$msg = $row['text'];
}
while($last_msg_id <= $old_msg_id)
{
usleep(1000);
clearstatcache();
$result = mysql_query("SELECT id, text FROM test ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$last_msg_id = $row['id'];
$msg = $row['text'];
}
}
$response = array();
$response['msg'] = $msg;
$response['old_msg_id'] = $last_msg_id;
$response = array_map('htmlentities',$response);
echo json_encode($response);