如何自动更新 Google Gauge [英] How to automatically update Google Gauge

查看:18
本文介绍了如何自动更新 Google Gauge的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这方面有点菜鸟,但我需要 Google Gauge 的帮助,它应该在数据库中获取最新条目并显示它,同时自动更新而无需重新加载站点.现在我有显示它的代码,但要更新为新值,我需要重新加载页面.

I'm kinda rookie in this, but I need help with Google Gauge that should take latest entry in database and display it, while updating automatically without the need to reload the site. Right now I have code that displays it, but for it to update to new values I need to reload the page.

这是我目前所拥有的:

<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 runs on the server, so it is only going to run once per page load.

无需重新加载页面即可更新图表,
您需要将 php 与 html/javascript 分开.

to update the chart without reloading the page,
you will need to separate the php from the html / javascript.

将 php 保存到不同的文件中,完全独立.

save the php to a different file, all by itself.

你需要在php中包含其余的数据,
包括列标题.

you need to include the rest of the data in the php,
including the column headings.

请参阅以下 php 代码片段.
例如,我们将文件命名为 --> getdata.php

see following snippet for the php.
for example purposes, we'll name the file --> 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

next, save the html / javascript to its own file.
for example purposes, we'll name the file --> chart.html

从php获取数据,
我们将使用 jquery ajax.

to get the data from php,
we'll use 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>

<小时>

编辑

需要确保 Value 列...

need to make sure the Value column...

是一个数字 --> 99.9594

is a number --> 99.9594

不是字符串 --> "99.9594"

not a string --> "99.9594"

您可以使用 --> (float)

you can convert using --> (float)

  // output data of each row
  while($row = mysqli_fetch_assoc($result)) {
      $data[] = ["ProductPurity", (float) $row["ProductPurity"]];
  }

和/或在编码语句中使用 JSON_NUMERIC_CHECK 常量...

and / or use the JSON_NUMERIC_CHECK constant on the encode statement...

echo json_encode($data, JSON_NUMERIC_CHECK);

这篇关于如何自动更新 Google Gauge的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆