【问题标题】:Google Charts (gague) display when no value in database谷歌图表(gague)在数据库中没有值时显示(已解决)
【发布时间】:2022-01-21 10:58:26
【问题描述】:

当我的数据库中没有值时,我想显示谷歌图表(仪表)。 我这样做的想法是在数组中插入一个虚拟值以显示图表,一旦将值添加到数据库中,就会覆盖它。但到目前为止我没有成功,有人可以帮我解决这个问题吗? 谢谢。(已解决)

postData.php

<?php require 'conn.php';?>

<?php
$sql = "SELECT * FROM sensors ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql) or die ($conn->error);

// create data array
$data = [];
$data[] = [["label"=>"Label","type"=>"string"],["label"=>"Value","type"=>"number"]];
 
// output data of each row
while ($row = $result->fetch_assoc() {
   $data[] = ["Temp", (float) $row["temp"]];   
}

// write data array to page
echo json_encode($data, JSON_NUMERIC_CHECK);
$result->free();
$conn->close();
?>

index.php

<script>
    google.charts.load('current', {
        packages: ['gauge']
    }).then(function () {
        var options = {
            width: 400, height: 400,
            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: 'postData.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>

<div id="chart_div" class="chart_hum" style="width: 400px; height: 120px;"></div>

【问题讨论】:

    标签: javascript php ajax


    【解决方案1】:

    我通过引用此link 并添加此代码解决了这个问题。我没有在 PHP 中使用数组,而是使用 JavaScript 添加虚拟值,一旦将数据插入数据库,它就会被覆盖。希望这对将来的某人有用。

     function drawChart() {
                $.ajax({
                    url: 'postData.php',
                    dataType: 'json'
                }).done(function (jsonData)     {
                       // use response from php for data table
                      var data = google.visualization.arrayToDataTable(jsonData);
                       // added part
                        if (data.getNumberOfRows() === 0) {
                       data.addRows([
                           ['Temp', 0]
                       ]);
                }
                      chart.draw(data, options);
    
                      // draw again in 5 seconds
                
                       window.setTimeout(drawChart, 5000);
                });
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多