【发布时间】:2018-04-02 18:48:36
【问题描述】:
我正在使用 Chart.js 插件创建一个条形图,其中包含按年份列出的销售额和采购值。这些值存储在 mysql 数据库中,我通过 PHP/AJAX 获取。
HTML
<canvas id="mybarChart"></canvas>
PHP
$sql = "SELECT YEAR(date) as years, SUM(amount) AS total FROM purchases GROUP BY YEAR(date)";
$res = mysql_query($sql);
$totalpurchases = [];
$sqll = "SELECT YEAR(date) as years, SUM(amount) AS total FROM sales GROUP BY YEAR(date)";
$ress = mysql_query($sqll);
$totalsales = [];
while($row = mysql_fetch_array($res)){
$totalpurchases[] = [$row['total']];
}
while($roww = mysql_fetch_array($ress)){
$totalsales[] = [$roww['total']];
}
echo json_encode(array($totalpurchases,$totalsales));
我的 JS 代码是这样的:
function show_chartbar(lbl01,lbl02){
var ctx = document.getElementById("mybarChart");
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["2013", "2014", "2015", "2016", "2017"],
datasets: [{
label: '# Total Purchase',
backgroundColor: "#26B99A",
data: lbl01
}, {
label: '# Total Sales',
backgroundColor: "#03586A",
data: lbl02
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
if ($('#mybarChart').length ){
$.ajax({
url: "scripts/values.php",
type: "GET",
dataType: "json",
success: function(resp)
{
var totpurchases = resp[0];
var totsales = resp[1];
console.log("Total Purchases: "+totpurchases);
console.log("Total Sales: "+totsales);
show_chartbar(totpurchases,totsales);
}
});
}
在控制台中正确显示值,但未显示在图表中:
我尝试在数据选项中添加额外的括号,但显示相同。
更新
console.dir(resp);
我该如何解决?我需要一些帮助。
【问题讨论】:
-
我想您的数据正在寻找一个数组,并且您从 json_encode 中取回一个对象,因为数组适用于键值对。您能否在您的 ajax 成功函数中
console.dir(resp)并向我们展示结果。谢谢。
标签: javascript php mysql chart.js bar-chart