【发布时间】:2019-06-23 15:31:31
【问题描述】:
基本上,我正在开发一个 ajax 聊天(php、mysql、javascript、ajax) 在部分代码中,我使用 ajax 获取 div 内的所有聊天消息,ajax 函数每 2 秒运行一次。
我的主要问题是 div 每 2 秒向下滚动一次,我需要它仅在有新条目时向下滚动(所有聊天用户都向下滚动,而不仅仅是我)
function loadLog(){
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
$.ajax({
url: "ajaxchat.php",
cache: false,
success: function(html){
$("#chatbox").html(html); //Insert chat log into the #chatbox div
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //i need to scroll if only there is new entry not every 2.5 sec
}
},
});
}
setInterval (loadLog, 2500); //Reload file every 2.5 seconds
【问题讨论】:
-
这种聊天系统需要实时服务器/客户端通信。但我认为您可以在这里做的不是每 2 秒加载一次所有消息,而是可以请求每 2 秒仅获取最近的消息,然后将该聊天推送到 dom。
-
你能举个例子吗?
标签: javascript php jquery html ajax