我尝试创建一个带有“新消息”计数器的个人消息系统...... 对于计数器我已经创建了一个MySQL函数:
function check_unread_messages($chat_id, $from_id) {
return (mysql_result(mysql_query("SELECT COUNT(*) FROM `messages` WHERE `group_id` = $chat_id AND `from_id` = $from_id AND `read_on` is NULL"), 0));
}
这就是调用函数的地方:
jQuery(document).ready(function() {
jQuery(setInterval(function() {
friends_count = document.getElementsByClassName("user").length;
for(var i=1; i < friends_count+1; i++) {
el = document.getElementById(i);
conv_id = el.getAttribute("data-user-id");
user_id = el.getAttribute("data-conv-id");
my_user_id = "<?php echo $session_user_id; ?>";
cache = "check_unread_messages("+conv_id+", "+user_id+")";
countMessages = "<?php "+cache+" ?>";
if(countMessages > 99) {
countMessages = "99+";
}
if(countMessages > 0 || countMessages == "99+") {
document.getElementById("badge-"+i).innerHTML = countMessages;
}
}
}, 500));
});
这是Count的容器:
<div class="user" id='<?php echo $i ?>' data-user-id='<?php echo $user_id?>' data-conv-id='<?php echo $conversation['id'] ?>'>
// something, that doesn't matter
<?php // normaly php gets opend in "something, that doesn't matter"
echo "<div class='rightCountUnreadMessages'>";
echo '<div class="badge" id="badge-'.$i.'"></div>';
echo "</div>";
?>
</div>
现在出现了我的问题...... 如果我尝试调试网站,输出尽可能多的信息,等等......我不知道,我做错了什么......
在Javascript函数中,我的用户ID user_id
和conv_id
是正确的,但我想,之后的2行有些错误('cache =“”...“)< / p>
你能帮助我解决这个问题还是给我一个更好的解决方案? :■ (抱歉我的英语不好,我不是母语人士......)
答案 0 :(得分:0)
尝试尽可能将JS与PHP分开,请查看以下有关如何使用AJAX请求执行此操作的示例。
创建名为check_unread_messages.php
的新PHP文件包含:
$chat_id = $_POST['chat_id'];
$from_id = $_POST['from_id'];
$query = mysqli_query("SELECT COUNT(*) FROM `messages` WHERE `group_id` = chat_id AND
`from_id` = $from_id AND `read_on` is NULL")
echo mysqli_result($query , 0);
使用ajax POST请求$.post()
调用它,如下所示:
$.post('check_unread_messages.php', {chat_id: conv_id, from_id: user_id}, function(result){
//Here you get response of echo mysqli_result($query , 0); responce in 'result' variable
})
希望这有帮助。