我在研究留言簿,我想知道是否有一种方法可以在有新消息时自动刷新。
所有帖子都存储在数据库中,并显示在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>