[英]AJAX Appending instead of using .HTML for my chat
So basically, my chat right now works like this:所以基本上,我现在的聊天是这样工作的:
Now here is the deal.现在是交易。 This seems very resource heavy, to load all the rows again and again and again.
这似乎非常耗费资源,一次又一次地加载所有行。 I know there is a way to optimize this, by using .append() function.
我知道有一种方法可以通过使用 .append() 函数来优化它。
All though, I can't seem to wrap my head around it.尽管如此,我似乎无法绕过它。
I need to make some kind of a counter, or a timestamp when the last message was loaded to check if there is newer content (rows) than since last time it loaded, if there is, append that new content.我需要在加载最后一条消息时制作某种计数器或时间戳,以检查是否存在比上次加载后更新的内容(行),如果有,则附加该新内容。
If I replace the .html function with .append, I will just keep getting the same messages over and over again, as right now.如果我用 .append 替换 .html 函数,我将一遍又一遍地收到相同的消息,就像现在一样。
How would I go about making this?我该怎么做呢?
Thanks in advance.提前致谢。
//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);
}
},
});
}
EXAMPLE OF WHAT LOADCHAT WILL SEND BACK: 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>
It should only send the var imAdmin variable once.它应该只发送一次 var imAdmin 变量。 (works with .html()).
(适用于 .html())。
Try using .slice()
尝试使用
.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>
Try making use of the 'data' attribute.尝试使用“数据”属性。 You could have something like 'data-timestamp' on each chat item and use that to work out what was placed when.
您可以在每个聊天项目上使用“数据时间戳”之类的内容,并使用它来计算放置时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.