[英]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.