【问题标题】:Uncaught TypeError: Cannot read property 'length' of null - Chart.js未捕获的类型错误:无法读取 null 的属性“长度”-Chart.js
【发布时间】:2019-01-28 18:42:02
【问题描述】:
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);
                });
            }
        });
    });

屏幕错误

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

【问题讨论】:

  • var ctx = document.getElementById(elementID) 而不是 '"' + elementID + '"' 也许
  • 是的,它的工作,谢谢!

标签: javascript ajax charts typeerror


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如果您不想使用 'lable' 或数据集配置的任何其他属性,也许您可​​以尝试使用以下代码

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 2023-03-13
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多