我使用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>
trefresh.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>
答案 0 :(得分:0)
检查代码中的if(req.status == 304),表示响应中没有修改。如果不是304则可以更新表格。
答案 1 :(得分:0)
首先,我想给你两个重要的建议:
答案:
后端:在项目中创建 EventLayer
它将从另一个实体收到一个发生新事件的信号,例如:您可以使用ActiveMQ OR 它会每隔N秒向外部实体发送一个请求以检查是否有某些内容new(您可以在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();
});
}