简体   繁体   English

解析Json以获取Google Charts条形图数据

[英]Parse Json for Google Charts Bar Chart Data

I have a google bar chart that I am trying to populate with data using PHP accessing a mySQL database but when I try and load my webpage I get the following error: 我有一个Google条形图,我试图使用PHP访问mySQL数据库来填充数据,但是当我尝试加载网页时,出现以下错误:

Uncaught (in promise) SyntaxError: Unexpected token u in JSON at position 0 at Function.parse [as parseJSON] 未捕获(承诺)SyntaxError:JSON中意外的令牌u在Function.parse的位置0 [作为parseJSON]

Here is what my PHP script currently returns: 这是我的PHP脚本当前返回的内容:

"['Priority', 'Automated', 'isAutomatable', 'isNotAutomatable'],""['All', 216, 861, 44],""['P1', 213, 568, 34],""['P2', 1, 148, 6],""['P3', 2, 136, 3],""['P4', 0, 7, 1],""['P5', 0, 2, 0],"

This is the chart I am looking to create: Clustered Column Chart 这是我要创建的图表聚集柱形图

You can find the chart here also: https://developers.google.com/chart/interactive/docs/gallery/columnchart under the " Creating Material column charts " section of the page 您也可以在此处找到该图表: https : //developers.google.com/chart/interactive/docs/gallery/columnchart在页面的“ 创建材料柱形图 ”部分下

I have included my HTML header where I am creating the google chart and the part of my PHP script where I am getting the data from my database. 我已经在创建Google图表的地方添加了HTML标头,并从数据库中获取了数据的PHP脚本部分。

HTML part HTML部分

  <script type="text/javascript">
    google.charts.load('current', {'packages':['bar']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
      var jsonData = $.ajax({
              url: "localhost:8080/getData.php",
              dataType: "json", // type of data we're expecting from server
              async: false // make true to avoid waiting for the request to be complete
      }).responseText;

      var data = google.visualization.arrayToDataTable($.parseJSON(jsonData));

      var options = {
        chart: {
          title: 'Automation of Tests Progression'
        }
      };

      var chart = new google.charts.Bar(document.getElementById('columnchart_material'));

      chart.draw(data, google.charts.Bar.convertOptions(options));
    }
  </script>

PHP script PHP脚本

    header('Access-Control_Allow-Origin: *');
    header('Content-Type: application/json');

    // Create connection and select db
    $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

    // Get data from database
    $result = $db->query("select platform,Priority,Automated,isAutomatable,isNotAutomatable,Total from automation_progress where platform = 'Cox' order by priority");

        #echo ['Priority', 'Automated', 'isAutomatable', 'isNotAutomatable'],
          if($result->num_rows > 0){
             echo json_encode("['Priority', 'Automated', 'isAutomatable', 'isNotAutomatable'],");
              while($row = $result->fetch_assoc()){
                echo json_encode ("['".$row['Priority']."', ".$row['Automated'].", ".$row['isAutomatable'].", ".$row['isNotAutomatable']."],");


  }
      }

UPDATE: 更新:

I have changed part of the PHP script to gather the results in an array and encode the array. 我更改了PHP脚本的一部分,以将结果收集到数组中并对该数组进行编码。 The data is now is now in correct JSON format but I am still seeing the same error when I try and return the data into the Google Chart. 现在,数据现在采用正确的JSON格式,但是当我尝试将数据返回到Google图表中时,仍然看到相同的错误。 The issue is happening in the HTML during: HTML中发生了此问题:

var data = google.visualization.arrayToDataTable($.parseJSON(jsonData));

You do not need to so such complicated stuff : just store all your data into an array in php and then encode it to json and echo it 您不需要这么复杂的东西:只需将所有数据存储到php中的数组中,然后将其编码为json并回显即可

if ($result->num_rows > 0) {
    $arrayToEncode = ['Priority', 'Automated', 'isAutomatable', 'isNotAutomatable'];
    while ($row = $result->fetch_assoc()) {
        $arrayToEncode[] = [$row['Priority'], $row['Automated'], $row['isAutomatable'], $row['isNotAutomatable']];
    }
    echo json_encode($arrayToEncode);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM