简体   繁体   English

Chart.js使用来自MySQL的json数据

[英]Chart.js using json data from MySQL

I am fairly new to Chart.js and I have tried a lot of different ways of doing this but I just can not seem to resolve loading data from JSON in to a bar type chart. 我对Chart.js相当陌生,我尝试了许多不同的方法来执行此操作,但我似乎无法解决将JSON中的数据加载到条形图中的问题。

I am trying to display a chart of monthly expenses with latest version of Chart.js. 我正在尝试显示Chart.js最新版本的每月费用图表。

The JSON string is as follows: 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"}]

My code is as follows: 我的代码如下:

$(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!");
        }
    });
}
 });

I can most likely imagine myself doing something very silly that is causing an undefined error, and I would love to see someone help me please. 我最有可能想象自己做的事情很愚蠢,导致未定义的错误,我很乐意看到有人请我帮忙。

Much appreciated and thank you. 非常感谢,谢谢。

Your chart does a POST? 您的图表执行POST吗?

Try something along that lines: 尝试以下方法:

$.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();
        }
    });
};

Minimal reproduction of your code seems to indicate that it is working fine, except the 2 options responsive and maintainAspectRatio (they works fine if the chart is contained in a div). 最小程度地复制代码似乎表明它工作正常,除了2个选项responsivemaintainAspectRatio (如果图表包含在div中,则它们工作正常)。 Copy and paste as a new html file into your web server to view. 复制并粘贴为新的html文件到您的Web服务器中进行查看。

Key changes made from your sample code: 根据您的示例代码进行的主要更改:

  • AJAX API call changed to GET from ./ AJAX API调用从./更改为GET
  • Added fake success data 添加了假的成功数据

Note: responsive and maintainAspectRatio seems to cause the chart to "tremble", unless the chart is wrapped in a div 注: responsivemaintainAspectRatio似乎会导致该图表以“颤抖”,除非图表被包裹在一个div

图表图片

The problem could lie in elsewhere, maybe in your server response? 问题可能出在其他地方,也许在您的服务器响应中?

<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>

In case anyone finds themselves in a similar position, I have highlighted the answer to the above problem below - thank you to wp78de and Edwin. 万一有人发现自己处于类似的位置,我在下面强调了上述问题的答案-感谢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!");
        }
    });
   }
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM