我有一个使用长轮询更新表格数据的div,除非我输入一段新文本,之前插入的文本始终首先出现且然后我刚写的内容。
所以,如果我写下你好,你好,再见,我会得到以下内容:
hi
hi
hello
hello
goodbye
相关的JS:
var timestamp = null;
function waitForMsg() {
$.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
async: true,
cache: false,
success:function(data) {
// alert(data);
var json = eval('('+data+')');
if (json['msg']) {
$('.chat_contacts .inner_chat').append(json['msg']+'<br>'); // MD
}
timestamp = json['timestamp'];
setTimeout('waitForMsg()', 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert('error '+textStatus+'('+errorThrown+')');
setTimeout('waitForMsg()', 1000);
}
});
}
update.php的相关摘录
$response = array();
while($row = mysqli_fetch_assoc($r)) {
$nou = $row['f1'];
$nru = $row['f2'];
$response['msg'] = $row['content'];
$response['timestamp'] = $row['time'];
}
echo json_encode($response);
为什么不只是检测输入的最后一件事并单独显示,而不重复输入的先前数据?
编辑: 我注意到了一些事情。
它似乎吞下了所输入的东西,所以如果表是空的,我写“嗨”,我得到你好,但如果我写“你好”,我再次“嗨”,然后如果我写了别的东西,我得到“你好”(而不是我刚写的东西)等等。
答案 0 :(得分:1)
将$response['msg'] = $row['content'];
替换为$response['msg'][] = $row['content'];
并更改JS
代码
if (json['msg']) {
$('.chat_contacts .inner_chat').append(json['msg'] + '<br>');
} // MD
使用
if (json['msg'].length) {
var el = $('.chat_contacts .inner_chat');
$.each(json['msg'], function(i, v) {
el.append(v + '<br>'); //MD
});
}
并确保sql query
您正在使用此类WHERE time > timestamp