1

简单地说,我想在菜单内的标签中显示未读消息的数量,如下所示:

 <li><a id="2" style="background-image:url('menu icons/comments.png'); background-repeat: no-repeat; background-position: left; background-position-x: 5px;"
                       href= "viewMessages.php">Messages<label id="num_msg">(<?php echo $count; ?>)</a></li>

我在哪里得到$count

$num_messages = mysql_query("SELECT COUNT(m.message_id) as cnt FROM messages m INNER JOIN member_message_member mmm ON (m.message_id = mmm.message_id)
                    WHERE mmm.member_id2 = $id AND m.seen = 0") or die(mysql_error());
                    $Mcount = mysql_fetch_assoc($num_messages);
                    $count = $Mcount['cnt'];

然后当用户点击消息时:

 $("#sub a").click(function(){
                    mesg_id = $(this).attr('msg_id');
                    page = $(this).attr('href')
                    id = $(this).attr('mID');
                    $.ajax ({
                            data: {message_id:mesg_id},
                            type: 'POST',
                            url:  'Seen_messages.php',
                            success: function(response) {
                                if (response == 1) {

                                } else {
                                    alert(response);
                                }
                            }
                        });
                });

Seen_messages.php:

@mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("mydb") or die(mysql_error());
    $message_id = $_POST['message_id'];
   mysql_query("UPDATE `messages` SET `messages`.`seen` = TRUE WHERE message_id={$message_id}") or die (mysql_error());
   echo "1";

一切正常,除了我必须刷新页面才能更新$count,那么无论如何要更新标签内的变量而无需手动刷新?

4

2 回答 2

3

Seen_messages.php使用更新的未读计数进行响应,而不是 always ,1然后使用该响应更新用户界面:

// ...
success: function(response) {
   if (isNaN(response)) {
       alert('Error!');
   } else {
       $('#num_msg').text(response);
   }
}
于 2012-07-01T22:43:34.120 回答
1

如何编写一个函数来setInterval()不断检查服务器是否有新消息,并<label>使用 jQuery 更新计数。(顺便说一句,您的标签缺少结束标签!)。

function get_msg_count(){
    $.ajax ({
        data: {}, // not really needed
        type: 'POST',
        url:  'get_msg_count.php', // page to return your msg count
        success: function(response) {
            // update the label with the count
            // response would be the number returned from PHP
            $('#num_msg').html(response); 
            }
        }); // End $.ajax
} // End Function

// and on DOM ready
$(function(){
    // check for new messages every 3 seconds(3000ms)
    setInterval(get_msg_count(), 3000) 
});

然后您的服务器端脚本将返回消息计数,您只需更新保存计数的标签。

于 2012-07-01T22:51:43.610 回答