我正在尝试构建一个聊天应用程序。但是我在尝试使用Node.js中的setInterval()函数定期刷新聊天页面时遇到了一个问题。以下是我的Ajax代码:
setInterval(function(){
//retreive user chat
$.ajax({
url: '/getMessage',
method: 'POST',
data : {receiver:receiver,sender:sender},
dataType:'json',
success: function(response){
let oldMessages = document.querySelectorAll('#textArea .incoming');
let messages = response.data;
let data = messages.map(message => {
let html = `<span class="chatMsg ${sender!=message.sender? 'incoming':'outgoing' }">${message.message}</span>`;
return html;
}).join(" ");
document.querySelector('#textArea').innerHTML = data;
let newMessages = document.querySelectorAll('#textArea .incoming');
console.log(`OLD ${oldMessages.length} NEW ${newMessages.length}`);
if(oldMessages.length > 0){
if(newMessages.length>oldMessages.length){
console.log(`RING- ${newMessages.length} ${oldMessages.length}`);
document.querySelector('#msg-new').play();
document.querySelector('#chatForm').scrollTop = document.querySelector('#chatForm').scrollHeight;
}
}
}
});
},5000);
}));
下面是我在routes / chat.js文件中的代码:
router.post('/getMessage',function(req,res){
Message.find(
{$or:[
{sender:req.body.sender,receiver:req.body.receiver},
{sender:req.body.receiver,receiver:req.body.sender}
]
},
(err,data) => {
res.send({success:true,data:data});
}
);
});
但是上面的代码无法在聊天列表中的用户之间切换时维护上下文。请帮助我及时刷新此页面。