【问题标题】:How to automatically update Google Gauge如何自动更新 Google Gauge
【发布时间】:2020-05-28 07:51:47
【问题描述】:

我在这方面有点菜鸟,但我需要 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>

【问题讨论】:

    标签: database charts google-visualization google-gauges


    【解决方案1】:

    php 在服务器上运行,因此每次页面加载它只会运行一次。

    在不重新加载页面的情况下更新图表,
    您需要将 php 与 html / javascript 分开。

    将 php 单独保存到不同的文件中。

    您需要在 php 中包含其余数据,
    包括列标题。

    请参阅下面的 sn-p 了解 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。

    看下面的sn-p...

    <!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列...

    是一个数字 --> 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);
    

    【讨论】:

    • 感谢您的回复。我试过这个,但是当我进入页面时它没有画任何东西。我能做些什么来解决它?
    • 我检查了 getdata.php 文件,它正在工作,当我在浏览器上运行它时它会返回:"[["Label","Value"],["ProductPurity","99.9594" ]]"
    猜你喜欢
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多