Google图表 - 表格没有列

时间:2017-02-27 08:44:59

标签: javascript php jquery ajax google-visualization

我被谷歌图表困住了 折线图显示两个值:TemperatureHumidity

由于我在图表中添加了ajax,因此它不再加载,我收到消息:

  

表没有列。

这是我的代码:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
  var jsonData = <?php echo json_encode($table); ?>;
  // Load the Visualization API and the piechart package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.setOnLoadCallback(drawChart);
  setInterval(drawChart, 10000);
  function drawChart() {
    $.ajax({
      url: 'getTemp.php',
      type: 'get',
      success: function (json) {
        var data = new google.visualization.DataTable(json);
        var options = {
          title: 'Raspberry:',
          curveType: 'function',
          'height':400
        };
        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    });
  };
</script>

编辑:这是我的php文件:getTemp.php,如果你需要别的东西让我知道。

$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {
    $result = $conn->query('SELECT * FROM Device_Data');
    $rows = array();
    $table = array();
    $table['cols'] = array(
                         array('label' => 'Timestamp', 'type' => 'string'),
                         array('label' => 'Temperature', 'type' => 'number'),
                         array('label' =>  'Humidity', 'type' => 'number')
                     );
    foreach($result as $r) {
        $data = array();
        $data[] = array('v' => (string) $r['Timestamp']);
        $data[] = array('v' => (int) $r['Temperature']);
        $data[] = array('v' => (int) $r['Humidity']);
        $rows[] = array('c' => $data);
    }
    $table['rows'] = $rows;
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

try {
    $result2 = $conn->prepare("SELECT 'Temperature','Humidity', 'Timestamp' from Device_Data;");      
    $result2->execute();
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

1 个答案:

答案 0 :(得分:1)

编辑/第二次尝试:

我认为变量超出了范围。

请直接申请<?php echo json_encode($table); ?>

看起来像:

var data = new google.visualization.DataTable(<?php echo json_encode($table); ?>);

然后,您可以删除旧的var jsonData ...部分,并删除成功函数中json的所有实例。