如何从网页(php)上的mysql数据库获取实时数据,以显示传感器的数据(无需刷新网页) 就像我有一个温度传感器,数据由传感器插入数据库。 我想在网页上显示最新数据,并进一步处理数据
[注意]
1)我有一个带有查询的普通index.php
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$sqlq="SELECT * FROM data WHERE id=(SELECT MAX(id) FROM data);
$row_result = mysqli_query($conn, $sqlq);
while($row = mysqli_fetch_assoc($row_result))
{
$id = $row['id'];
$num = $row['num'];
echo $id." | ".$num;
}
[输出]
12 | 36
但我必须刷新页面才能获得最新数据 没有刷新页面的任何解决方案?
答案 0 :(得分:0)
使用javascript ajax GET-request接收数据。
function load_data() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("data_output").text = this.responseText;
}
};
xhttp.open("GET", "output.php", true);
xhttp.send();
}
window.setInterval (load_data, 1000); //1 second interval

<div id="data_output"></div>
&#13;
你的output.php看起来像是:
$conn = mysqli_connect ($dbhost, $dbuser, $dbpass, $dbname);
if (!$conn)
die ("Connection failed: ".mysqli_connect_error ());
$sqlq = "SELECT *
FROM data
ORDER BY id DESC
LIMIT 0,1";
$row_result = mysqli_query ($conn, $sqlq);
$row = mysqli_fetch_assoc ($row_result);
echo $row['id']." | ".$row['num'];