未捕获的TypeError:无法读取null的属性“长度”-Chart.js

时间:2018-08-22 13:24:29

标签: javascript ajax charts typeerror

function createChart(elementID, chartLabels, chartData) {
        var ctx = document.getElementById('"' + elementID + '"');
        var myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: chartLabels,
                datasets: [{
                    label: '',
                    data: chartData,
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        });
    }

    $(document).ready(function () {
        $.ajax({
            type: 'GET',
            url: '/my-progress/charts-data-load/',
            success: function (data) {
                $.each(data.data, function (k, v) {
                    let sections = [];
                    let section_total = [];
                    let section_correct = [];
                    let chart_id = v.chart_id;
                    let course = v.course;
                    let chart_data = v.chart_data;
                    $.each(chart_data, function (i, j) {
                        sections.push(j.section);
                        section_total.push(j.section_total);
                        section_correct.push(j.section_correct);
                    });
                    let chart_identifier = 'chart-'+chart_id;
                    $('.charts-wrapper').append(
                        '<div class="col-6">\n' +
                        '    <canvas id="'+chart_identifier+'" width="400" height="400"></canvas>\n' +
                        '</div>'
                    );
                    console.log(sections);
                    console.log(section_total);
                    console.log(section_correct);
                    console.log(chart_identifier);
                    createChart(chart_identifier, sections, section_correct);
                });
            }
        });
    });

屏幕error中的错误

数据来自后端,我想根据这些数据使用Chart.js来构建图表。在日志中,您可以看到有数据输入。Dalle我为日程表绘制了画布。数据被发送到绘制图形的函数。

2 个答案:

答案 0 :(得分:0)

If you don't want to use 'lable' or any other property of dataset config maybe you can try with following code

var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: options
});

答案 1 :(得分:0)

var ctx = document.getElementById(elementID)而不是var ctx = document.getElementById('"' + elementID + '"')