gpt4 book ai didi

javascript - 使用 php 在 AJAX 中进行长轮询

转载 作者:行者123 更新时间:2023-11-28 06:23:14 25 4
gpt4 key购买 nike

我正在使用 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>

最佳答案

检查代码中的 if(req.status == 304),这表示响应没有修改。如果不是 304 那么您可以更新表。

关于javascript - 使用 php 在 AJAX 中进行长轮询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35339391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com