我有一个Google条形图,我试图使用PHP访问mySQL数据库来填充数据,但是当我尝试加载网页时,出现以下错误:
未捕获(承诺)SyntaxError:JSON中的意外令牌u在 位置0 在Function.parse [as 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],"
这是我要创建的图表: Clustered Column Chart
您还可以在这里找到图表: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));
答案 0 :(得分:0)
您不需要这么复杂的东西:只需将所有数据存储到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);
}