我正在使用AJAX
通过AJAX刷新页面的某些部分,这样我就不必一次又一次地重新加载页面。
但是我希望表仅在发生变化(长轮询)时才刷新。但我不知道该怎么做。我尝试使用带有 break 语句的 for 循环,但我猜没有得到正确的逻辑。
这些文件如下
getuser.php
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$conn = mysqli_connect('localhost','root','','bondplus');
if (!$conn) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($conn,"bondplus");
$sql="SELECT * FROM `user_details`";
$result = mysqli_query($conn,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Mobile</th>
<th>Email</th>
<th>Type</th>
<th>Hometown</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['u_name'] . "</td>";
echo "<td>" . $row['mob'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
</body>
</html>
提神.php
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>AJAX Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="reloader.js"></script>
</head>
<body onload="reloadData()">
<p> HELLO There!</p>
<div id="currentData" align="center">
<p>Loading Data...</p>
</div>
</body>
<script>
var req;
function reloadData()
{
var now = new Date();
url = 'getuser.php?' + now.getTime();
try {
req = new XMLHttpRequest();
} catch (e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (oc) {
alert("No AJAX Support");
return;
}
}
}
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send(null);
}
function processReqChange()
{
// If req shows "complete"
if (req.readyState == 4)
{
dataDiv = document.getElementById('currentData');
// If "OK"
if (req.status == 200)
{
// Set current data text
dataDiv.innerHTML = req.responseText;
// Start new timer (1 min)
timeoutID = setTimeout('reloadData()', 6000);
}
else
{
// Flag error
dataDiv.innerHTML = '<p>There was a problem retrieving data: ' + req.statusText + '</p>';
}
}
}
</script>
</html>
检查代码中的 if(req.status == 304),它表示响应中没有修改。如果不是 304,则可以更新表。
首先,我想给你2个重要的建议:
答:
后端:在项目中创建事件层
它将从另一个实体接收新事物发生的信号,例如:您可以使用 ActiveMQ 或者它将每 N 秒向外部实体发送一个请求以检查是否有新内容(您可以将标志存储在 memcache 或同步数据源服务器中,如 ANYEM),然后刷新数据(数据创建将是, 当然是由业务层创建的)
前端非常简单,您将在自己的 Ajax 上循环,示例
function ajaxLongPollingManager() {
$.ajax({
url: "yourproject.event.php"
}).done(function(response) {
// do your job ....
// ...
// and loop back
ajaxLongPollingManager();
}).fail(function(response) {
// manage/handle your errors
// ...
// and loop back
ajaxLongPollingManager();
});
}