database - 如何自动更新 Google Gauge
问题描述
我在这方面有点菜鸟,但我需要谷歌仪表的帮助,它应该在数据库中获取最新条目并显示它,同时自动更新而无需重新加载站点。现在我有显示它的代码,但要更新为新值,我需要重新加载页面。
这是我到目前为止所拥有的:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['gauge']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['ProductPurity', <?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["ProductPurity"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?> ],
]);
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(data, options);
setInterval(function() {
data.setValue(0 ,1 , <?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["ProductPurity"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
);
chart.draw(data, options);
}, 5000);
setInterval(function() {
data.setValue(1, 1, 40 + Math.round(60 * Math.random()));
chart.draw(data, options);
}, 5000);
setInterval(function() {
data.setValue(2, 1, 60 + Math.round(20 * Math.random()));
chart.draw(data, options);
}, 26000);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 400px; height: 120px;"></div>
</body>
</html>
解决方案
php 在服务器上运行,因此每次页面加载只会运行一次。
要在不重新加载页面的情况下更新图表,
您需要将 php 与 html / javascript 分开。
将 php 单独保存到不同的文件中。
您需要在 php 中包含其余数据,
包括列标题。
请参阅以下 php 代码段。
例如,我们将文件命名为 -->getdata.php
<?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
// create data array
$data = [];
$data[] = ["Label", "Value"];
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", $row["ProductPurity"]];
}
mysqli_close($conn);
// write data array to page
echo json_encode($data);
?>
接下来,将 html/javascript 保存到自己的文件中。
例如,我们将文件命名为 -->chart.html
要从 php 获取数据,
我们将使用 jquery ajax。
请参阅以下片段...
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData);
chart.draw(data, options);
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
</head>
<body>
<div id="chart_div" style="width: 400px; height: 120px;"></div>
</body>
</html>
编辑
需要确保值列...
是一个数字 -->99.9594
不是字符串 -->"99.9594"
您可以使用 --> 进行转换(float)
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
}
和/或JSON_NUMERIC_CHECK
在编码语句上使用常量...
echo json_encode($data, JSON_NUMERIC_CHECK);
推荐阅读
- avfoundation - 在 iOS 应用程序中更新下载的 HLS 文件的最佳方法是什么?
- graphql - Gatsby / GraphQL 应用程序 - 部署时的渲染和样式问题(Netlify 和 Surge)
- coc.nvim - CoC:诊断窗口接管屏幕
- c - 最小脚本 Dev-C++ 上的“未定义对‘WinMain’的引用”错误
- reactjs - 如何使用 AWS coginto auth sdk 刷新令牌
- git - Git回滚合并提交
- python - 我如何确保不同的最终用户在 PythonAnywhere 中同时访问我的程序时将他们的文件/程序状态保留给自己
- javascript - 在 for 循环 VueJS 中同步 API 调用
- reactjs - 协助 React useState hook 暂时为空/空数据
- java - 转换 2 个相同对象后抛出 Java ClassCastException