如何知道 AJAX 是否已获取新数据?



我正在制作一个聊天网站。我使用 AJAX 每 2 秒获取一次聊天消息。我还使用 scrollTop: 在数据加载时自动滚动页面。但是我似乎无法弄清楚如何在新消息到达而不是每 2 秒到达时才自动滚动。

$('.contact').click(function() {
$('.cont').not(this).removeClass('active');
$(this).toggleClass('active');
sendRequest();
function sendRequest(){
var convo_id=document.getElementById("convo_id").value;
$.ajax({
cache: false,
type: "POST",
url: 'show_chat.php',
data: ({convo_id: convo_id}),
success: function(response) {
$('#chatgoeshere').html(response);
$(".messages").animate({ scrollTop: $(document).height() }, "fast");},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(sendRequest, 2000); // The interval set to 5 seconds
}
});
};
});

谢谢

将您的服务器响应从简单的 HTML 转换为对象,并在此聊天中包含消息总数:

{ html: "yourHtml", messagesCount: yourMessagesCount }

然后在 JavaScript 中将旧计数与接收计数进行比较,如果为 true,则更新内容

if(oldMessages < response.messagesCount)

也仅在有新消息时才更新内容,如果没有新消息,您将重新呈现页面并浪费资源:)

在此行中

success: function(response) {

您需要检查响应。 如果您获得一些数据,则可以向上滚动页面。

检查响应是否不为空,然后添加滚动函数

if response
{
$('#chatgoeshere').html(response);
$(".messages").animate({ scrollTop: $(document).height() }, "fast");},
}

最新更新