我正在尝试从PHP网页创建的JSON生成饼图,但出现“无数据”错误。我对JavaScript的经验很少,我可能无法正确地将数据加载到图表中。
我尝试创建一个JSON文件并加载它,而不是PHP,但这并没有改变任何内容。我想让JSON输出尽可能地接近Google Visual Pie Chart示例,以使该示例尽可能简单。
所有文件(数据库连接除外)都位于同一文件夹中。
getData.php
<?php
require_once("../../lib/db_connectPDOfinance.php");
$sql = "SELECT * FROM players_test";
$sth = $dbh->prepare($sql);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$ar = [];
array_push($ar, array('Player', 'Score'));
if (isset($result)) foreach($result as $row)
{
$player = $row['player'];
$player = $player;
$score = (int)$row['score'];
array_push($ar, array($player, $score));
}
$out = array_values($ar);
echo json_encode($out);
?>
getData.php的输出
[["Player","Score"],["Ace",27],["Bob",21],["Chris",25],["Dave",21],["James",25],["Joe",34]]
graph.html
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
data = new google.visualization.DataTable();
data.addColumn('string', 'Player');
data.addColumn('number', 'Score');
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
});
var options = {
title: 'Experience Distribution'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
预期输出是饼图,实际输出是统计图标题(经验分布)和文本“无数据”。统计图将是
答案 0 :(得分:0)
已解决(参考:Creating Pie Chart with Google Charts API from JSON)
我没有将数据加载到graph.html中,我只是告诉它数据在哪里。
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
data = new google.visualization.DataTable();
data.addColumn('string', 'Player');
data.addColumn('number', 'Score');
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).done(function (results) {
Object.keys(results).forEach(function (index) {
data.addRow([
results[index][0],
parseInt(results[index][1])
]);
});
});
var options = {
title: 'Experience Distribution'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>