javascript - Bar Chart.js 不显示 PHP、MySQL、AJAX 的值

标签 javascript php mysql chart.js bar-chart

我正在使用 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);
        }
    });

}

在控制台中,它正确显示了值,但没有显示在图表中:

enter image description here

我试图在数据选项中添加额外的括号,但它显示相同。

更新

console.dir(resp);

enter image description here

我该如何解决?我需要一些帮助。

最佳答案

您正在创建一个数组的数组。我相信这会解决这个问题。

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/

相关文章:

MYSQL 从选择和变量中插入

php - 从模型名称获取模块名称

php - Symfony 2.7.4 Twig 错误

mysql - 在删除级联 MySQL 时删除

javascript - 当有人点击搜索结果链接时,Google 如何设置 HTTP Referrer?

javascript - 在这种情况下,我如何理解 Promise all?

javascript - 表操作

javascript - 如何使用 Javascript SDK 调用带有参数的云代码函数

php - MySQL/PHP 多查询 : 3 statements, 2 个结果

php - 从 mysql 表加载图像