weixin_33716941 2015-06-16 08:09 采纳率: 0%
浏览 59

如何自动刷新留言簿?

我在研究留言簿,我想知道是否有一种方法可以在有新消息时自动刷新。

所有帖子都存储在数据库中,并显示在html表中:

 echo "<table class=\"guestbook\" cellspacing='10'>";

        while($rows=mysql_fetch_array($result)) {
            $avatar = $Database->selectAvatar($rows['name']);
            $rowsAvatar=mysql_fetch_array($avatar)

            ?>
        <tr>
            <td class="avatar" width="10%"><img class="circolare" src="<?php echo $rowsAvatar['avatar'] ?>"></td>
            <td class="name" width="10%"><?php echo $rows['name']; ?></td>
            <td class="datetime" width="20%"><?php echo $rows['datetime']; ?></td>
            <td class="comment" width="50%"><div class="scrollbar"><?php echo $rows['comment']; ?></div></td>
            <td class="delete" width="10%"><?php
                if($rows['name']== $name){
                    echo "<a href=\"deletecomment.php?comment_id=" .  $rows['id'] ."\">Delete it</a>";
                }
                ?>
            </td>
        </tr>


        <?php
        }
        echo "</table >";
        ?>

我想要自动更新这个表,该怎么办?首先,我尝试每5秒使用一次自动刷新,但问题是,如果用户正在写一篇文章(它位于同一页中的表单),那么页面刷新就会丢失。我想我必须使用Ajax,对吗?有什么建议吗?

我试图用Ajax实现它:

window.onload = function(){
    interval = window.setInterval('updateGuest()',5000);
}



function updateGuest() {
    $.ajax({
        url: 'getGuest.php',
        method: 'get',
        success: on_getGuest_success,
        error: on_error
    });
}

function on_getGuest_success(data) {
    for(var i=0; i<data.length;i++) {
       //do something
    }

}

function on_error() {
   //do something

}

getGuest.php

<?php

include("Database.php");

$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");

$result = $Database->selectQuery("guestbook", "*");

$rows=mysql_fetch_array($result);

echo json_encode($rows);
?>

我已经在home.php中包含了所有脚本:

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="jquery-1.11.3.js" type="text/javascript"></script>
    <script src="Script.js" type="text/javascript"></script>
</head>
  • 写回答

1条回答 默认 最新

  • 关注

    You could use jQuery to check every few seconds if there is a new post (by using a get or ajax call).

    If there is a new post, you could append it to the table. That way the page won't have to refresh, and the person writing a post can continue.

    If you are not familiar with the mentioned techniques, I recommend you look them up and try to implement them, since they are often used.

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料