gpt4 book ai didi

javascript - 如何使用ajax刷新聊天记录

转载 作者:行者123 更新时间:2023-12-01 00:15:57 25 4
gpt4 key购买 nike

我正在基于 twilio api 实现文本聊天,我有以下功能可以在单击时加载聊天、发送消息、获取最后一条消息(将间隔设置为 1 秒以实时更新),并且我将添加检查是否数据未设置,不执行任何其他操作,获取最后一条消息,我需要获取当前点击项的数据值

这是脚本和日志

[![<script type="text/javascript">
$(document).ready(function(){
loadContacts();
displayChatOnclick();
setInterval(getlastmsg,1000);
}
);
//when the user clicks on contacts div fetch the chat history
function displayChatOnclick(){
$('#contacts').on('click','li',function() {
var channel = $(this).closest('li').attr('data-channel');
var name=$(this).closest('li').attr('data-name');
console.log(channel);
fetchChat(channel,name);
sendmsg();
//check if new msg is sent
});
}
function fetchChat(channel,name){
$.ajax({
url: 'loadchat.php',
type: 'POST',
data: { channel:channel,name:name },


success: function(msg) {
console.log(name);
$('#conversation').html(msg);
}
});
}
function loadContacts(){
$.ajax({
url: 'loadcontacts.php',
type: 'POST',


success: function(msg) {
$('#contacts').html(msg);
}
});
}
//function to get the last msg
function getlastmsg(){
var channel = $('#contacts li').data('data-channel');
var name=$('#contacts li').data('data-name');



//check if channel and name is null do nothing else fetch last message

console.log(name);




}
//function to send a msg
function sendmsg(){

$("#send").click(function() {
var channel=$(this).data('ch');
var message=$("#msg").val();
$('#msg').val('');

console.log(msg);
$.ajax({
type: "POST",
url: "sendmsg.php",
data: {
msg: message,
channel:channel,

},
success: function(result) {
console.log("sent");
$('#b').append(result);
}
});
});
}

</script>][1]][1]

最佳答案

你正在做的是一个拉方法:setInterval不是最好的主意,因为它会不断地调用你的服务器,不管有没有改变,想象一下如果你有1000个用户它们每一秒都会向服务器发送一个请求。

我建议您使用推送方法,例如SignalRhere is a demo for chat that you can do with small number of lines

关于javascript - 如何使用ajax刷新聊天记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59763808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com