Google图表 - 不绘制图表 - 未定义数据表

时间:2017-02-27 11:26:12

标签: javascript php json ajax google-visualization

我为我的Google图表设置了一个使用Ajax的Interval,但图表并未被绘制。我只收到消息:"数据表未定义。"每5秒钟。 Picture of the Meessage.

Google Chart来源:

    <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">

// 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, 5000);

function load_page_data(){
 $.ajax({
    url: 'getTemp.php',
    type: 'get',
    success: function (json) {
      var data = new google.visualization.DataTable(<?php echo json_encode($table); ?>);


       var options = {
        title: 'Raspberry:',
        curveType: 'function',
        'height':400
    };
    },
    });
}
     function drawChart() {
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw();

     }

 </script>

从MySQL获取数据的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 :(得分:0)

in chart.draw();你必须提供数据表和选项

chart.draw(dataTable, options);