【问题标题】:How can I process the ajax request only when needed, not every amount of sec如何仅在需要时才处理 ajax 请求,而不是每秒钟
【发布时间】: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


【解决方案1】:

一个简单的解决方案是在更新 chatbox 之前检查新 HTML 与旧 HTML 是否不同。这将确保 chatbox 仅在从服务器获取新内容时更新。但是,如果您的响应 HTML 不一致,这将不起作用。

var previousChatHTML = '';
function showChatMessages(html) {
    if(previousChatHTML === html){
        return;
    }
    var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
    $("#chatbox").html(html); //Insert chat log into the #chatbox div  
    previousChatHTML = html;   
    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 
    }               
}

function loadLog(){     
    $.ajax({
        url: "ajaxchat.php",
        cache: false,
        success: showChatMessages,
    });
}
setInterval (loadLog, 2500);    //Reload file every 2.5 seconds

此外,在 JS 中创建轮询器时,您可能希望使用 setTimeout (https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) 而不是 setInterval,因为在慢速连接上您可能会得到奇怪的结果(如果请求花费的时间超过 2.5 秒,它可能会以错误的顺序解决)。

【讨论】:

    【解决方案2】:

    LAMP 无法做到这一点 您需要响应来自服务器的事件。 你可以用这个堆栈做到这一点


    您的服务器需要响应数据库事件。 PHP 对客户端事件的响应。

    【讨论】:

    • 你有办法让我只有在聊天中有新条目时才能向下滚动 div,而不是总是向下滚动
    猜你喜欢
    • 2015-10-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 2018-08-05
    相关资源
    最近更新 更多