window.setInterval(function(){
$.post ('<?php echo base_url(); ?>ClientCont/List_Files/fetchmessage',
{
id:folderid
},
function(data){
console.log(data);
if(data.length > 0){
var a;
for(a = 0; a < data.length; a++){
$('#previouscomment').append("<div id = 'dateconvo' style = 'margin-top:20px;text-align:center;color:#D3D3D3'>" + data[a]['date_entry'] + "</div><br>" +
"<input id = 'oldid' type = 'hidden' value = " + data[a]['comment_id'] + ">" +
"<div id = 'usernamemessage' style = 'color:#D3D3D3'>" + atob(data[a]['name_user']) + "</div>" +
"<div id = 'messageme' style = 'margin-left:10px;margin-top:10px;border-radius: .4em;background-color: #4CAF50!important; border-radius: 5px;box-shadow: 0 0 6px #B2B2B2; display: inline-block;padding: 10px 18px;position: relative;vertical-align: top;color:#FFFFFF'>" +
data[a]['message']) + "\n";
}
}else{
$('#previouscomment').append("<div align = 'center' style = 'margin-top:30px;color:#D3D3D3'><img src = '<?php echo base_url();?>assets/images/nocommentyet.png' align = 'middle' style = 'height:100px;width:100px;'/>" + "<br>NO COMMENT TO DISPLAY</div>");
}
$("#previouscomment").animate({ scrollTop: "2000000000000px" }, "fast");
},
'json'
);
},1000);
我有以下代码,但遗憾的是每分钟它都会附加消息......甚至是之前附加的消息。
我只想问一下如何在每次执行代码时避免消息的冗余。它应该只获取新消息。
答案 0 :(得分:0)
在你的代码中,你定义了循环,它正在读取响应中的所有对象,并且每个附加元素都没有唯一的id,所以我们将为每个附加的div分配一个唯一的id,我们将从中获取在您的情况下,我们将使用comment_id
,在追加之前,我们将检查此元素是否已存在
window.setInterval(function() {
$.post('<?php echo base_url(); ?>ClientCont/List_Files/fetchmessage', {
id: folderid
}, function(data) {
console.log(data);
if (data.length > 0) {
var a;
for (a = 0; a < data.length; a++) {
if ($('#dateconvo' + data[a]['comment_id']).length == 0) {
$('#previouscomment').append("<div id = 'dateconvo" + data[a]['comment_id'] + "' style = 'margin-top:20px;text-align:center;color:#D3D3D3'>" + data[a]['date_entry'] + "</div><br>" +
"<input id = 'oldid' type = 'hidden' value = " + data[a]['comment_id'] + ">" +
"<div id = 'usernamemessage' style = 'color:#D3D3D3'>" + atob(data[a]['name_user']) + "</div>" +
"<div id = 'messageme' style = 'margin-left:10px;margin-top:10px;border-radius: .4em;background-color: #4CAF50!important; border-radius: 5px;box-shadow: 0 0 6px #B2B2B2; display: inline-block;padding: 10px 18px;position: relative;vertical-align: top;color:#FFFFFF'>" +
data[a]['message']) + "\n";
}
}
} else {
$('#previouscomment').append("<div align = 'center' style = 'margin-top:30px;color:#D3D3D3'><img src = '<?php echo base_url();?>assets/images/nocommentyet.png' align = 'middle' style = 'height:100px;width:100px;'/>" + "<br>NO COMMENT TO DISPLAY</div>");
}
$("#previouscomment").animate({
scrollTop: "2000000000000px"
}, "fast");
}, 'json');
}, 1000);