Helloo,我一直在做一个项目,我必须每10秒刷新一次数据,我已经创建了一个单独的文件来加载一个信息,并且该文件有效,但是我的问题是,我的数据库中有3个传感器数据,我是否需要创建3个不同的刷新文件才能将每个数据加载到我的主页上?
这是我的数据文件之一:
<?php
session_start();
include_once 'includes/dbh.inc.php';
$id = $_SESSION['userId'];
$dBname = "infosensor";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
$sql = "SELECT * FROM `$id` ORDER BY id DESC LIMIT 1;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
$ss1 = intval($row['sensor1'] * ($p = pow(10, 2))) / $p;
echo "".$ss1."A";
$s1 = $row['sensor1'];
}
}
?>
这是我的更新文件:
<script type="text/javascript" src="jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
setInterval(function () {
$('#p0-blocoCorrente').load('load.php')
}, 5000);
});
</script>
这就是我的显示方式:
<div class="blocoCorrente" id = "blocoCorrente">
<!-- Imprimir os valore dos sensor 1 -->
<div class="p0-blocoshow">Corrente 1:</div>
<div class="p0-blocoCorrente" id ="p0-blocoCorrente"></div>
</div>
更新:
session_start();
include_once 'includes/dbh.inc.php';
$id = $_SESSION['userId'];
$sensor = isset($_POST['sensor']) ? "sensor" . intval($_POST['sensor']) : "sensor1";
$dBname = "infosensor";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
$sql = "SELECT $sensor FROM `$id` ORDER BY id DESC LIMIT 1;";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if($row)
{
$s1 = $row[$sensor];
$ss1 = intval($s1 * ($p = pow(10, 2))) / $p;
echo $ss1;
}
$sensor1 = isset($_POST['sensor']) ? "sensor" . intval($_POST['sensor']) : "sensor2";
$sql = "SELECT $sensor1 FROM `$id` ORDER BY id DESC LIMIT 1;";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if($row)
{
$s2 = $row[$sensor1];
$ss2 = intval($s1 * ($p = pow(10, 2))) / $p;
echo $ss2;
}
答案 0 :(得分:0)
使PHP脚本返回JSON对象中的所有传感器。然后,您可以在适当的DIV中显示它们中的每一个。
session_start();
include_once 'includes/dbh.inc.php';
$id = $_SESSION['userId'];
$dBname = "infosensor";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
$sql = "SELECT sensor1, sensor2, sensor3 FROM `$id` ORDER BY id DESC LIMIT 1;";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$sensors = array();
if($row)
{
for ($i = 1; $i <= 3; $i++) {
$s1 = $row["sensor$i"];
$ss1 = intval($s1 * ($p = pow(10, 2))) / $p;
$sensors["sensor$i"] = $ss1 . "A";
}
echo json_encode($sensors);
} else {
echo json_encode(null);
}
然后将JavaScript更改为使用$.getJSON()
。
$(document).ready(function (){
setInterval(function () {
$.getJSON('load.php', function(sensors) {
if (sensors) {
$('#p0-blocoCorrente').text(sensors.sensor1);
$('#p1-blocoCorrente').text(sensors.sensor2);
$('#p2-blocoCorrente').text(sensors.sensor3);
}
});
}, 5000);
});