0

我有一个管理门户,我们可以在其中查看注册了多少用户。数据存储在 MySQL 中。

当 mySQL 表中有新数据可用时,我需要自动追加一个新行,而无需重新加载整个页面

<table>
    <tr>
    <th>NAME</th>
    </th>Register Time </th>
     </tr>

     <?php
     while($row=mysql_fetch_array(mysql_query("SELECT * FROM `register`"))){
         echo '<tr>';
         echo '<td>'.$row['name'].'</td>';
          echo '<td>'.$row['reg_time'].'</td>';
          echo '</tr>';
     }
     echo '</table>';
4

1 回答 1

1

不要使用mysql_*函数。改为使用mysqli_*什么时候应该使用 MySQLi 而不是 MySQL?

结果页面:

<table class="users">
    <tr>
        <th>NAME</th>
        </th>Register Time </th>
    </tr>

<?php

$query = mysql_query("SELECT * FROM `register`");
$lastId = 0;
while ($row = mysql_fetch_array($query)) {
    $lastId = $row['id'];
    echo '<tr>';
    echo '<td>'.$row['name'].'</td>';
    echo '<td>'.$row['reg_time'].'</td>';
    echo '</tr>';
}
echo '</table>';
echo '<script>var lastId = '. $lastId .'</script>'; // remember the last id

?>

在同一页面加载的 Javascript:

$(document).ready(function() {
    var usersTable = $(".users");

    setInterval(function() {
        $.ajax({
            url: 'get_users.php?id='+lastId,
            dataType: 'json',
            success: function(json) {
                if (json.length > 0) {
                    $.each(json, function(key, user) {
                        usersTable.append('<tr><td>'+user.name+'</td><td>'+user.reg_time+'</td></tr>');
                        lastId = user.id;
                    });
                }
            }
        });
    }, 10000);
});

get_users.php:

$lastId = (int)$_GET['id'];

$query = mysql_query('SELECT * FROM `register` WHERE `id` >' . $lastId);
$result = array();

while ($row = mysql_fetch_array($query)) {
    $result[] = $row;
}

echo json_encode($result);

要点是每X秒进行一次 ajax 调用,并附加在当前页面上最后一个用户之后注册的所有用户。

读书:

于 2013-07-16T20:23:39.557 回答