【问题标题】:Chart.js using json data from MySQLChart.js 使用来自 MySQL 的 json 数据
【发布时间】:2018-04-10 00:42:52
【问题描述】:

我对 Chart.js 还很陌生,我尝试了很多不同的方法,但我似乎无法解决将 JSON 中的数据加载到条形图表中的问题。

我正在尝试使用最新版本的 Chart.js 显示每月费用图表。

JSON字符串如下:

[{"month":"Jan","amount":"0.00"},{"month":"Feb","amount":"0.00"},{"month":"Mar","amount":"100.00"},{"month":"Apr","amount":"0.00"},{"month":"May","amount":"0.00"},{"month":"Jun","amount":"977.00"},{"month":"Jul","amount":"0.00"},{"month":"Aug","amount":"0.00"},{"month":"Sep","amount":"0.00"},{"month":"Oct","amount":"0.00"},{"month":"Nov","amount":"0.00"},{"month":"Dec","amount":"0.00"}]

我的代码如下:

$(function () {
var chartColors = {
    red: 'rgba(255, 99, 132, 1)',
    blue: 'rgba(54, 162, 235, 1)',
    yellow: 'rgba(255, 205, 86, 1)',
    green: 'rgba(75, 192, 192, 1)',
    purple: 'rgba(153, 102, 255, 1)',
    orange: 'rgba(255, 159, 64, 1)',
    darkgrey: 'rgba(102, 102, 102, 1)',
    maroon: 'rgba(200, 112, 91, 1)',
    khaki: 'rgba(190, 204, 200, 1)'
};

if( $("#ChartExpenseBar").length > 0 ){
    $.ajax({
        type: 'POST',
        url: '/expenses/',
        data: {'expense_chart': 'monthly'},
        success: function(data) {
            var months = [];
            var amount = [];

            for (var i in data) {
                months.push(data[i].month);
                amount.push(data[i].amount);
            }

            var ctx = document.getElementById("ChartExpenseBar").getContext('2d');
            var myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    //labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
                    labels: months,
                    datasets: [{
                        label: 'Monthly expenses',
                        backgroundColor: [
                            chartColors.red,
                            chartColors.blue,
                            chartColors.yellow,
                            chartColors.purple,
                            chartColors.green,
                            chartColors.orange,
                            chartColors.red,
                            chartColors.blue,
                            chartColors.yellow,
                            chartColors.purple,
                            chartColors.green,
                            chartColors.orange
                        ],
                        borderColor: [
                            chartColors.red,
                            chartColors.blue,
                            chartColors.yellow,
                            chartColors.purple,
                            chartColors.green,
                            chartColors.orange,
                            chartColors.red,
                            chartColors.blue,
                            chartColors.yellow,
                            chartColors.purple,
                            chartColors.green,
                            chartColors.orange
                        ],
                        borderWidth: 1,
                        data: amount
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    tooltips: {
                        displayColors: false,
                        callbacks: {
                            // use label callback to return the desired label
                            label: function(tooltipItem, data) {
                                return "£" + tooltipItem.yLabel;
                            },
                            // remove title
                            title: function(tooltipItem, data) {
                                return;
                            }
                        }
                    },
                    legend: {
                        display: false
                    },
                    scales: {
                        xAxes: [{
                            gridLines: {
                                display: false
                            }
                        }],
                        yAxes: [{
                            gridLines: {
                                display: false
                            },
                            ticks: {
                                beginAtZero:true,
                                userCallback: function(value, index, values) {
                                    // Convert the number to a string and splite the string every 3 charaters from the end
                                    value = value.toString();
                                    value = value.split(/(?=(?:...)*$)/);

                                    // Convert the array to a string and format the output
                                    value = value.join('.');
                                    return '£' + value;
                                }
                            }
                        }]
                    }
                }
            });
        },
        error: function() {
            alert("There is a problem with loading the chart!");
        }
    });
}
 });

我很可能会想象自己做了一些非常愚蠢的事情,导致了一个未定义的错误,我很想看到有人帮助我。

非常感谢,谢谢。

【问题讨论】:

    标签: javascript jquery charts chart.js bar-chart


    【解决方案1】:

    您的图表执行 POST 吗?

    尝试类似的方法:

    $.ajax({
      url: '/expenses/',
      async: false,
      dataType: 'json',
      type: "GET",
      success: function (d) {
               chartData = {
                    labels: d.AxisLabels,
                    datasets: [
                        {
                            fillColor: "rgba(220,220,220,0.5)",
                            strokeColor: "rgba(220,220,220,1)",
                            pointColor: "rgba(220,220,220,1)",
                            pointStrokeColor: "#fff",
                            data: d.DataSets[0]
                        }
                    ]
                };
    
                max = Math.max.apply(Math, d.DataSets[0]);
                steps = 10;
    
                respondCanvas();
            }
        });
    };
    

    【讨论】:

    • 你是一个救生员。我将类型更改为 GET,以下两个是游戏规则改变者:async: false 和 dataType: 'json'。工作就像一种享受 - 非常感谢!
    【解决方案2】:

    您的代码的最小复制似乎表明它工作正常,除了 responsivemaintainAspectRatio 2 个选项(如果图表包含在 div 中,它们工作正常)。将新的 html 文件复制并粘贴到您的网络服务器中以进行查看。

    对您的示例代码所做的主要更改:

    • AJAX API 调用更改为 GET from ./
    • 添加了虚假成功数据

    注意: responsivemaintainAspectRatio 似乎会导致图表“颤抖”,除非图表包裹在 div 中

    问题可能出在其他地方,也许在您的服务器响应中?

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <script
        src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js" integrity="sha256-JG6hsuMjFnQ2spWq0UiaDRJBaarzhFbUxiUTxQDA9Lk=" crossorigin="anonymous"></script>
    <div style="width:500px;">
        <canvas id="ChartExpenseBar" width="200" height="200"></canvas>
    </div>
    <script>
    
        $(function () {
        var chartColors = {
            red: 'rgba(255, 99, 132, 1)',
            blue: 'rgba(54, 162, 235, 1)',
            yellow: 'rgba(255, 205, 86, 1)',
            green: 'rgba(75, 192, 192, 1)',
            purple: 'rgba(153, 102, 255, 1)',
            orange: 'rgba(255, 159, 64, 1)',
            darkgrey: 'rgba(102, 102, 102, 1)',
            maroon: 'rgba(200, 112, 91, 1)',
            khaki: 'rgba(190, 204, 200, 1)'
        };
    
        if( $("#ChartExpenseBar").length > 0 ){
            $.ajax({
                type: 'GET',
                url: './',
                data: {'expense_chart': 'monthly'},
                success: function(data) {
                    var months = [];
                    var amount = [];
                    // fill with fake data
                    data = [{"month":"Jan","amount":"0.00"},{"month":"Feb","amount":"0.00"},{"month":"Mar","amount":"100.00"},{"month":"Apr","amount":"0.00"},{"month":"May","amount":"0.00"},{"month":"Jun","amount":"977.00"},{"month":"Jul","amount":"0.00"},{"month":"Aug","amount":"0.00"},{"month":"Sep","amount":"0.00"},{"month":"Oct","amount":"0.00"},{"month":"Nov","amount":"0.00"},{"month":"Dec","amount":"0.00"}];
                    for (var i in data) {
                        months.push(data[i].month);
                        amount.push(data[i].amount);
                    }
    
                    var ctx = document.getElementById("ChartExpenseBar").getContext('2d');
                    var myChart = new Chart(ctx, {
                        type: 'bar',
                        data: {
                            //labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
                            labels: months,
                            datasets: [{
                                label: 'Monthly expenses',
                                backgroundColor: [
                                    chartColors.red,
                                    chartColors.blue,
                                    chartColors.yellow,
                                    chartColors.purple,
                                    chartColors.green,
                                    chartColors.orange,
                                    chartColors.red,
                                    chartColors.blue,
                                    chartColors.yellow,
                                    chartColors.purple,
                                    chartColors.green,
                                    chartColors.orange
                                ],
                                borderColor: [
                                    chartColors.red,
                                    chartColors.blue,
                                    chartColors.yellow,
                                    chartColors.purple,
                                    chartColors.green,
                                    chartColors.orange,
                                    chartColors.red,
                                    chartColors.blue,
                                    chartColors.yellow,
                                    chartColors.purple,
                                    chartColors.green,
                                    chartColors.orange
                                ],
                                borderWidth: 1,
                                data: amount
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            tooltips: {
                                displayColors: false,
                                callbacks: {
                                    // use label callback to return the desired label
                                    label: function(tooltipItem, data) {
                                        return "£" + tooltipItem.yLabel;
                                    },
                                    // remove title
                                    title: function(tooltipItem, data) {
                                        return;
                                    }
                                }
                            },
                            legend: {
                                display: false
                            },
                            scales: {
                                xAxes: [{
                                    gridLines: {
                                        display: false
                                    }
                                }],
                                yAxes: [{
                                    gridLines: {
                                        display: false
                                    },
                                    ticks: {
                                        beginAtZero:true,
                                        userCallback: function(value, index, values) {
                                            // Convert the number to a string and splite the string every 3 charaters from the end
                                            value = value.toString();
                                            value = value.split(/(?=(?:...)*$)/);
    
                                            // Convert the array to a string and format the output
                                            value = value.join('.');
                                            return '£' + value;
                                        }
                                    }
                                }]
                            }
                        }
                    });
                },
                error: function() {
                    alert("There is a problem with loading the chart!");
                }
            });
        }
        });
    
    </script>
    

    【讨论】:

    • 嗨 Edwin,让我快速尝试一下 - 非常感谢!
    • 您好,埃德温,感谢您的帮助。请参考下面的答案,我也根据您的建议将类型更改为 GET。
    • @Cam 这意味着您的服务器未配置为使用 POST 方法响应该 API 调用。 :) 很高兴我能帮上忙。
    【解决方案3】:

    如果有人发现自己处于类似的位置,我在下面突出显示了上述问题的答案 - 感谢 wp78de 和 Edwin。

      $(function () {
    var chartColors = {
        red: 'rgba(255, 99, 132, 1)',
        blue: 'rgba(54, 162, 235, 1)',
        yellow: 'rgba(255, 205, 86, 1)',
        green: 'rgba(75, 192, 192, 1)',
        purple: 'rgba(153, 102, 255, 1)',
        orange: 'rgba(255, 159, 64, 1)',
        darkgrey: 'rgba(102, 102, 102, 1)',
        maroon: 'rgba(200, 112, 91, 1)',
        khaki: 'rgba(190, 204, 200, 1)'
    };
    
    if( $("#ChartExpenseBar").length > 0 ){
        $.ajax({
            type: 'GET',
            async: false,
            dataType: 'json',
            url: '/expenses/',
            data: {'expense_chart': 'monthly'},
            success: function(data) {
                var months = [];
                var amount = [];
    
                for (var i in data) {
                    months.push(data[i].month);
                    amount.push(data[i].amount);
                }
    
                var ctx = document.getElementById("ChartExpenseBar").getContext('2d');
                var myChart = new Chart(ctx, {
                    type: 'bar',
                    data: {                    
                        labels: months,
                        datasets: [{
                            label: 'Monthly expenses',
                            backgroundColor: [
                                chartColors.red,
                                chartColors.blue,
                                chartColors.yellow,
                                chartColors.purple,
                                chartColors.green,
                                chartColors.orange,
                                chartColors.red,
                                chartColors.blue,
                                chartColors.yellow,
                                chartColors.purple,
                                chartColors.green,
                                chartColors.orange
                            ],
                            borderColor: [
                                chartColors.red,
                                chartColors.blue,
                                chartColors.yellow,
                                chartColors.purple,
                                chartColors.green,
                                chartColors.orange,
                                chartColors.red,
                                chartColors.blue,
                                chartColors.yellow,
                                chartColors.purple,
                                chartColors.green,
                                chartColors.orange
                            ],
                            borderWidth: 1,
                            data: amount
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        tooltips: {
                            displayColors: false,
                            callbacks: {
                                // use label callback to return the desired label
                                label: function(tooltipItem, data) {
                                    return "£" + tooltipItem.yLabel;
                                },
                                // remove title
                                title: function(tooltipItem, data) {
                                    return;
                                }
                            }
                        },
                        legend: {
                            display: false
                        },
                        scales: {
                            xAxes: [{
                                gridLines: {
                                    display: false
                                }
                            }],
                            yAxes: [{
                                gridLines: {
                                    display: false
                                },
                                ticks: {
                                    beginAtZero:true,
                                    userCallback: function(value, index, values) {
                                        // Convert the number to a string and splite the string every 3 charaters from the end
                                        value = value.toString();
                                        value = value.split(/(?=(?:...)*$)/);
    
                                        // Convert the array to a string and format the output
                                        value = value.join('.');
                                        return '£' + value;
                                    }
                                }
                            }]
                        }
                    }
                });
            },
            error: function() {
                alert("There is a problem with loading the chart!");
            }
        });
       }
     });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多