我每30秒使用JavaScript函数setInterval
来检查AJAX的MySQL表。使用AJAX可以用新结果更新页面,而无需重新加载页面。
我想使用效果highlight
为某些记录着色,在下面的示例中突出显示了ID 1和10:
$("#image_li_1").effect("highlight", {}, 25000);
$("#image_li_10").effect("highlight", {}, 25000);
我想突出显示自上次加载以来添加的所有新记录。
index.php
// Run polling function every 60 seconds
var myVar = setInterval(myfunction, 30000);
// Load data from check_status page
function myfunction() {
$.ajax({
url: "check_status.php", success: function(result2) {
$("#div2").html(result2);
$("#title").html("Food Items AUTO Poll");
$("#image_li_1").effect("highlight", {}, 25000);
$("#image_li_10").effect("highlight", {}, 25000);
}
});
}
check_status.php
// Include and create instance of db class
require_once 'DB.class.php';
$db = new DB();
<?php
// Fetch all items from database
$data = $db->getRows();
if (!empty($data)) {
foreach ($data as $row) {
?>
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle">
<a href="javascript:void(0);" style="float:none;" class="image_link">
<?php echo $row['name']; ?>
</a>
</li>
<?php
}
}
?>
DB.class.php
<?php
class DB {
// Database configuration
private $dbHost = "###";
private $dbUsername = "###";
private $dbPassword = "###";
private $dbName = "###";
private $itemTbl = "###";
function __construct() {
if (!isset($this->db)) {
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if ($conn->connect_error) {
die("Failed to connect with MySQL: " . $conn->connect_error);
} else {
$this->db = $conn;
}
}
}
// Get rows from data table
function getRows() {
$query = $this->db->query("SELECT * FROM ".$this->itemTbl." ORDER BY img_order ASC");
if ($query->num_rows > 0) {
while ($row = $query->fetch_assoc()) {
$result[] = $row;
}
} else {
$result = FALSE;
}
return $result;
}
答案 0 :(得分:2)
尝试搜索和阅读类似“创建REST服务php”的内容。您应该了解这种方法的主要思想。通常,您的代码应如下所示:
php.php
<?php
$yourDatabaseClass = new YourDatabaseClass("localhost", "username", "password", "database");
$data = $yourDatabaseClass->getTable("select * from table");
echo json_encode($data);
您的js:
var oldData = [];
var currentData = [];
var yourElement = document.getElementById('application');
client.doRequest("php.php").then(function(response){
currentData = response;
renderData();
})
function renderData() {
yourElement.innerHTML = '';
currentData.forEach(function(item){
if(isNew(item)) {
yourElement.apendChild(createHighlightedData(item));
} else {
yourElement.apendChild(createOrdinarData(item));
}
})
}
function createHighlightedData(item) {
return ...
}
function createOrdinarData(item) {
return ...
}