AJAX附加,而不是使用.html为我的聊天

AJAX Appending instead of using .HTML for my chat

本文关键字:html 我的 聊天 附加 AJAX      更新时间:2023-09-26

现在我的聊天工具是这样的

  • 每隔一秒它检查我的PHP文件loadchat.php。
  • Loadchat.php将获取每一行比他们的会话更新。
  • 它然后替换所有当前数据在我的div: #chatbox使用. html()函数。

事情是这样的。这似乎非常资源繁重,一次又一次地加载所有行。我知道有一种方法可以优化这一点,通过使用。append()函数。

尽管如此,我似乎还是无法理解。

我需要做一个计数器,或者一个时间戳,当最后一条消息被加载时,检查是否有更新的内容(行),如果有,附加新内容。

如果我将。html函数替换为。append,我将一遍又一遍地得到相同的消息,就像现在一样。

我该怎么做呢?

提前感谢。

//AJAX Timeout Loop Load Chat Function:
function loadChat() {
  $.ajax({
    method: 'POST',
    url: 'ajax/load_chat.php',
    success: function(data) {
      $('#chatbox').html(data);
      //console.log($('#chatbox')[0].scrollHeight - $('#chatbox').innerHeight());
      //console.log($('#chatbox').scrollTop());
      if(atBottom) {
        $("#chatbox").stop().animate({ scrollTop: $('#chatbox')[0].scrollHeight}, 500);
      }
    },    
  });
}

LOADCHAT返回的示例:

<script type="text/javascript">var imAdmin = true</script>
<div data-chat-sid="76561198216640736" data-chat-msid="76561198216640736" data-chat-sun="deinhoin" class="chat-box__content--single chat-box--mychat">
  <div class="chat-box__content__single--avatar">
     <div class="admin" style="background-image:url(https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/83/83b9e88c1f88451dcc97d2537416bbd413247ad6_full.jpg);"><span>Mod</span></div>
  </div>
  <div class="chat-box__content__single--title">deinhoin</div>
  <div class="chat-box__content__single--message">adada</div>
</div>

它应该只发送一次var imAdmin变量。(适用于。html())。

尝试使用.slice()

// `section` : container for chat message elements
var html = $("section div");
// `data` : `html` returned from server
var data = "<div>1</div><div>2</div><div>3</div>";
// if `data` `.length` greater than existing `section` `div` `.length`,
if ($(data).length > $(html).length) {
  // `.slice()` elements greater than existing `section div` length
  var newdata = $(data).slice($(html).length);
  // append new elements to `section div`
  $("section").append(newdata);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section>
<div>1</div><div>2</div>
  </section>

尝试使用'data'属性。您可以在每个聊天项上设置类似'data-timestamp'的东西,并使用它来计算当。