您好我有一个工作脚本为我的小型聊天应用程序检索JSON数据结果,但我的问题是它显示已发布的文本的重复结果以及从我的数据库中插入的新文本
这是我的整个Javascript代码:
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = AjaxRetrieve();
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.ajax({
url: "includes/getChat.php",
type: "GET",
data: data,
dataType: 'json',
success: function(result){
$.each(result, function(rowKey, row) {
$("#clog").append($('<p />').html('<h4>'+ row.username +':</h4>' + row.message_content) );
});
}
});
}
答案 0 :(得分:2)
我认为你的getChat.php返回该用户的所有聊天文本,你也将它们附加到#clog。
我有两个建议
通过从JS本身发送时间戳(如
),仅从服务器返回最新文本data = {"chat": uid, "rid": rid, "name": user, "last_read_time": window.last_read_time};
window.last_read_time = new Date().format("d/M/yyyy hh:mm:ss tt"); //store new time
在循环数据之前清除#clog
$("#clog").empty(); //clear the previous msgs
$.each(result, function(rowKey, row) {
$("#clog").append($('<p />').html('<h4>'+ row.username +':</h4>' + row.message_content);
});