【发布时间】:2021-04-15 16:09:45
【问题描述】:
我正在尝试使用 Google Charts 生成饼图,我想要使用的数据位于 MySQL 数据库中,因此我创建了一个脚本来获取该数据并将其解析为 JSON,然后理想情况下将填充图表。
我已经创建了脚本并检查了它是否接收到数据并且它是 JSON 格式,但我得到的只是“表没有列”,任何人都可以看到我哪里出错了吗?
显示图表的页面
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var jsonData = $.ajax({
url: "scripts/charts/popularColours.php",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
稍后在同一页面上:
<div id="chart_colours"></div>
我的 popularColours.php 页面
$dsn = "";
$options = [
PDO::ATTR_EMULATE_PREPARES => false, // turn off emulation mode for "real" prepared statements
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
$pdo = new PDO($dsn, "dbu300121", "3DD63tJXYpP%", $options);
} catch (Exception $e) {
error_log($e->getMessage());
exit('There has been an unexpected error, please try again last if the issue continues then contact your IT Support team.'); //something a user can understand
}
$statement = $pdo->prepare("SELECT veh_colour, COUNT(*) as col FROM cst_vehicle GROUP BY veh_colour ORDER BY 2 DESC LIMIT 6");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo $json;
您可以看到,这是返回的数据
[{"veh_colour":null,"col":206},{"veh_colour":"Black Pearl","col":9},{"veh_colour":"dynamic red","col":8},{"veh_colour":"Battersea Blue","col":6},{"veh_colour":"Arctic White","col":6},{"veh_colour":"Laser Blue","col":5}]
【问题讨论】:
-
为了从 json 创建 google 数据表,它必须是特定格式,found here。否则,您可以提供一个简单的数组并使用arrayToDataTable 创建数据表。注意:
$.ajax上的async: false已被弃用,请改用done回调。检查this answer...
标签: php json pdo google-visualization