我正在使用 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);
我该如何解决?我需要一些帮助。
最佳答案
您正在创建一个数组的数组。我相信这会解决这个问题。
while($row = mysql_fetch_array($res)){
$totalpurchases[] = $row['total'];
}
while($roww = mysql_fetch_array($ress)){
$totalsales[] = $roww['total'];
}
关于javascript - Bar Chart.js 不显示 PHP、MySQL、AJAX 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49616972/