我有一个由AJAX调用填写的表。我想要做的是追加任何进入数据库的新数据,我似乎无法长时间轮询工作,但这可能是因为我还在学习并且没有做好,所以任何帮助将不胜感激!
我遇到的麻烦,最初并没有填写表格,而是在将数据输入数据库后用新数据更新/附加。
我的PHP:
<?php
DEFINE('DB_USERNAME', 'root');
DEFINE('DB_PASSWORD', 'root');
DEFINE('DB_HOST', 'localhost');
DEFINE('DB_DATABASE', 'silent auction');
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_error()) {
die('Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
}
$arr = array();
$total_owed;
$bidders;
$query = "SELECT * FROM users";
$sql = $mysqli->query($query);
if($sql->num_rows > 0) {
while($row = $sql->fetch_assoc()){
$bidders++;
$arr[] = $row;
$total_owed += $row['amount_owed'];
}
}
echo json_encode(array($arr, $total_owed, $bidders));
?>
我的JavaScript:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'getData.php',
dataType: 'json',
cache: false,
success: function(response) {
for(var i = 0; i < response[0].length; i++) {
$('#bidders').append('<tr><td>' + response[0][i]['id'] + '</td><td>' + response[0][i]['first_name'] + " " + response[0][i]['last_name'] + '</td><td>' + response[0][i]['table'] + '</td><td>' + response[0][i]['items_won'] + '</td><td>' + response[0][i]['pledges_made'] +'</td><td>' + response[0][i]['amount_owed'] + '</td><td><button class="btn btn-primary">CLICK HERE</button></td></tr>');
}
$('#amount').text(response[1]);
$('#paymentsTotal').text(response[2]);
}
});
});
我的HTML(数据附加到的地方):
<section id='bidderTable' class='container-fluid'>
<h1 class='text-center'>Winning Bidders</h1>
<table class='table'>
<thead>
<tr>
<th scope='col'>#</th>
<th scope='col'>Name</th>
<th scope='col'>Table</th>
<th scope='col'>No. Items Won</th>
<th scope='col'>Pledges</th>
<th scope='col'>Amount Owed</th>
<th scope='col'>Invoice</th>
</tr>
</thead>
<tbody id='bidders'>
</tbody>
</table>
</section>
答案 0 :(得分:3)
您应该通过查询数据库以固定的时间间隔更新HTML表。您现在只在页面加载时加载表。
您应该使用javascript的setInterval()
。您可以根据需要配置时间。
$(document).ready(function () {
setInterval(function() {
reloadTable()
}, 5000); // This will load data every 5 seconds
});
function reloadTable(){
$.ajax({
type: 'GET',
url: 'getData.php',
dataType: 'json',
cache: false,
success: function(response) {
// This will clear table of the old data other than the header row
$("#bidders").find("tr:gt(0)").remove();
for(var i = 0; i < response[0].length; i++) {
$('#bidders').append('<tr><td>' + response[0][i]['id'] + '</td><td>' + response[0][i]['first_name'] + " " + response[0][i]['last_name'] + '</td><td>' + response[0][i]['table'] + '</td><td>' + response[0][i]['items_won'] + '</td><td>' + response[0][i]['pledges_made'] +'</td><td>' + response[0][i]['amount_owed'] + '</td><td><button class="btn btn-primary">CLICK HERE</button></td></tr>');
}
$('#amount').text(response[1]);
$('#paymentsTotal').text(response[2]);
}
});
}