这是我的代码
<!doctype html>
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
<style>
*{padding:0px; margin:0px;}
#output{width:850px; height:400px; background-color:#E0F5CD; margin:auto;}
#tbl{position:relative; top:30px;}
</style>
</head>
<body>
<div id="output"></div>
<script id="source" language="javascript" type="text/javascript">
$('#output').append("<br /><h3><center>Employee Table</center></h3>");
$.ajax({
url: 'ajax_db.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var employee_name = row[1];
var email = row[2];
var message = row[3];
var date = row[4];
$('#output').append(
"<table border=1 width='850' id='tbl'border=1 width='850' id='tbl'>" +
"<tr>" +
"<td width='25%'>" + employee_name + "</td>" +
"<td width='25%'>" + email + "</td>" +
"<td width='25%'>" + message + "</td>" +
"<td width='25%'>" + date + "</td>" +
"</tr>" +
"</table>");
}
}
});
</script>
<script>
</script>
</body>
</html>
我想要一个只加载id为#output的div的代码,而不加载整个页面。 div必须每2秒自动刷新一次。我调用了api.php,它包含从数据库中提取的数据,显示5行。 如果我删除一行,则必须在2秒后显示更新的数据。 这是我的代码ajax_db.php
<?php
mysql_connect("localhost", "root", "root") || die(mysql_error());
mysql_select_db("bijit") || die(mysql_error());
$result = mysql_query("SELECT * FROM employee ORDER BY id DESC LIMIT 5");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
?>
请建议我最简单的代码。
答案 0 :(得分:1)
我刚刚修改了你的代码。我用html()更改了第一个append(),并将所有内容放在一个函数中,这样我们就可以每隔2秒调用一次。
<script id="source" language="javascript" type="text/javascript">
(function refresh() {
$("#output").html("<br /><h3><center>Employee Table</center></h3>");
$.ajax({
url: 'ajax_db.php', data: "", dataType: 'json', success: function(rows) {
for (var i in rows) {
var row = rows[i];
var employee_name = row[1];
var email = row[2];
var message = row[3];
var date = row[4];
$("#output").append("<table border=1 width='850' id='tbl'>" +
"<tr>" +
"<td width='25%'>" + employee_name + "</td>" +
"<td width='25%'>" + email + "</td>" +
"<td width='25%'>" + message + "</td>" +
"<td width='25%'>" + date + "</td>" +
"</tr>" +
"</table>");
}
}
});
setInterval(refresh, 2000);
})();
</script>
答案 1 :(得分:0)
您可能需要每两秒钟获取一次新数据,
function explode(){
///......your ajax load function and append code here
}
setTimeout(explode, 2000);