[英]Parse Json for Google Charts Bar Chart Data
我有一个Google条形图,我试图使用PHP访问mySQL数据库来填充数据,但是当我尝试加载网页时,出现以下错误:
未捕获(承诺)SyntaxError:JSON中意外的令牌u在Function.parse的位置0 [作为parseJSON]
这是我的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],"
您也可以在此处找到该图表: https : //developers.google.com/chart/interactive/docs/gallery/columnchart在页面的“ 创建材料柱形图 ”部分下
我已经在创建Google图表的地方添加了HTML标头,并从数据库中获取了数据的PHP脚本部分。
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脚本
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']."],");
}
}
更新:
我更改了PHP脚本的一部分,以将结果收集到数组中并对该数组进行编码。 现在,数据现在采用正确的JSON格式,但是当我尝试将数据返回到Google图表中时,仍然看到相同的错误。 HTML中发生了此问题:
var data = google.visualization.arrayToDataTable($.parseJSON(jsonData));
您不需要这么复杂的东西:只需将所有数据存储到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.