大家好,我正在尝试与 Jquery、php、ajax 和 mysql 建立聊天,这几天以来我面临的问题是,当我获得最后一条消息的值时,它不断追加到 div 我想要的是追加最后一条消息只有一次,如果有新消息,则再次追加这里是我的 ajax 调用
var chat = "";
$.ajax({
url: "php/gt_user.php",
type: "get",
success: function (result) {
var gtUser = $.parseJSON(result);
$.each(gtUser, function (idx, obj) {
var usrApp = "<span><i class='fa fa-user-circle-o' aria-hidden='true'></i>";
usrApp += "<p class='usr-name'>" + obj.Tables_in_chat + "</p></span>";
$('.userarea').append(usrApp);
}); // here i get all the username who sent a message and print them on a div
$('.userarea span').on('click', function () {
$('.msgarea').html("");
var usrName = $(this).text();
$('#usrname').text(usrName);
setInterval(function () {
$.ajax({
url: "php/admin_msg.php",
type: "post",
data: {
name: usrName
},
success: function (result) {
var lastmsg = result;
function appedn() {
var usrMsg = "<div class='usr-msg'><i class='fa fa-user-circle-o' aria-hidden='true'></i>";
usrMsg += "<span><p>" + lastmsg + "</p></span></div>";
$('.msgarea').append(usrMsg);
}
if (chat !== result) {
appedn();
} else {
chat = result;
}
}
});
}, 2000);
});
}
});
respanse fromphp/admin_msg.php
正在工作,我成功地收到了最后一条消息问题是这个脚本不断向消息区域添加相同的消息,我想要的是如果有新消息只添加一次消息
经过 1 天的斗争,我终于能够解决这个问题,所以我会在这里发布 answear 以防万一它会帮助其他人面临同样的问题
我必须从数据库中获取所有用户名表的部分我将它移动到我的 HTML 并使用几行 php 来回显这样的结果(每个用户名都有自己的表)
// show all the user name that sent a message
$result = $con->query("show tables from chat");
while($row = mysqli_fetch_assoc($result)){
echo "<span><i class='fa fa-user-circle-o' aria-hidden='true'></i><p class='usr-name'>".$row['Tables_in_chat']."</p></span>";
}
然后在我的 jquery 脚本中,我移动了在点击事件之外每 2 秒检查最后一条消息的函数,这样我的 Jquery 脚本现在看起来更干净
/* get the user name and added it to the header of the message box */
$('.userarea span').on('click', function () {
$('.msgarea').html("");
var usrName = $(this).text();
$('#usrname').text(usrName);
});
var chatdata = "";
/* check for new message and append the message area if there is a new one */
setInterval(function () {
var usrName = $('#usrname').text();
$.ajax({
url: "php/admin_msg.php",
type: "post",
data: {
name: usrName
},
success: function (result) {
function appedn() {
var usrMsg = "<div class='usr-msg'><i class='fa fa-user-circle-o' aria-hidden='true'></i>";
usrMsg += "<span><p>" + result + "</p></span></div>";
$('.msgarea').append(usrMsg);
}
if (chatdata !== result) {
appedn();
chatdata = result;
}
}
});
}, 2000);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句