jquery Chart Js无法读取未定义的属性“length”

iugsix8n  于 2023-04-05  发布在  jQuery
关注(0)|答案(8)|浏览(202)

使用Chart js我试图从 AJAX 调用中提取数据以提供给Chart。我发现了一些其他帖子,人们建议延迟画布加载,但似乎没有任何工作。目前这是我下面的内容,我得到的错误是

$(function () {

GetChartData();

    function GetChartData() {
    $.ajax({
        url: ajaxURL,
        method: 'GET',
        dataType: 'json',
        success: function (d) {
            //-------------
            //- BAR CHART -
            //-------------
            var barChartData = d;
            var barChartCanvas = $("#barChart").get(0).getContext("2d");
            var barChart = new Chart(barChartCanvas);
            // console.log(datajson);
            //barChartData.datasets[1].fillColor = "#00a65a";
            //barChartData.datasets[1].strokeColor = "#00a65a";
            //barChartData.datasets[1].pointColor = "#00a65a";
            var barChartOptions = {
                //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
                //scaleBeginAtZero: true,
                //Boolean - Whether grid lines are shown across the chart
                scaleShowGridLines: true,
                //String - Colour of the grid lines
                scaleGridLineColor: "rgba(0,0,0,.05)",
                //Number - Width of the grid lines
                scaleGridLineWidth: 1,
                //Boolean - Whether to show horizontal lines (except X axis)
                scaleShowHorizontalLines: true,
                //Boolean - Whether to show vertical lines (except Y axis)
                scaleShowVerticalLines: true,
                //Boolean - If there is a stroke on each bar
                barShowStroke: true,
                //Number - Pixel width of the bar stroke
                barStrokeWidth: 2,
                //Number - Spacing between each of the X value sets
                barValueSpacing: 5,
                //Number - Spacing between data sets within X values
                barDatasetSpacing: 1,
                multiTooltipTemplate: "<%=datasetLabel%>: <%= value + ' %' %>",
                //String - A legend template
                legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
                //Boolean - whether to make the chart responsive
                responsive: true,
                maintainAspectRatio: true
            };

            barChartOptions.datasetFill = false;
            barChart.Bar(barChartData, barChartOptions);

        }
    });
    }
});

此处更新显示非 AJAX 如何工作

下面的代码是获取 AJAX get请求的结果(我将其转储到控制台)并创建相同内容的“硬编码”版本。唯一在技术上应该不同的是,一个是在页面加载时加载数据,而第二个是在页面加载后非常短暂地加载数据。

var chartData = {
    "labels": [
      "April"
    ],
    "datasets": [
      {
          "label": "Not Sure What to Put Here",
          "fillColor": "#662B60",
          "strokeColor": "#662B60",
          "pointColor": "#662B60",
          "pointStrokeColor": "#662B60",
          "pointHighlightFill": "#662B60",
          "pointHighlightStroke": "#662B60",
          "data": [
            1
          ]
      },
      {
          "label": "Not Sure What to Put Here",
          "fillColor": "#88B56E",
          "strokeColor": "#88B56E",
          "pointColor": "#88B56E",
          "pointStrokeColor": "#88B56E",
          "pointHighlightFill": "#88B56E",
          "pointHighlightStroke": "#88B56E",
          "data": [
            1
          ]
      },
      {
          "label": "Not Sure What to Put Here",
          "fillColor": "#48CA2B",
          "strokeColor": "#48CA2B",
          "pointColor": "#48CA2B",
          "pointStrokeColor": "#48CA2B",
          "pointHighlightFill": "#48CA2B",
          "pointHighlightStroke": "#48CA2B",
          "data": [
            0.83
          ]
      }
    ]
};

    //-------------
    //- BAR CHART -
    //-------------
var barChartData = chartData;
    var barChartCanvas = $("#barChart").get(0).getContext("2d");
    var barChart = new Chart(barChartCanvas);

    //barChartData.datasets[1].fillColor = "#00a65a";
    //barChartData.datasets[1].strokeColor = "#00a65a";
    //barChartData.datasets[1].pointColor = "#00a65a";
    var barChartOptions = {
        //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
        //scaleBeginAtZero: true,
        //Boolean - Whether grid lines are shown across the chart
        scaleShowGridLines: true,
        //String - Colour of the grid lines
        scaleGridLineColor: "rgba(0,0,0,.05)",
        //Number - Width of the grid lines
        scaleGridLineWidth: 1,
        //Boolean - Whether to show horizontal lines (except X axis)
        scaleShowHorizontalLines: true,
        //Boolean - Whether to show vertical lines (except Y axis)
        scaleShowVerticalLines: true,
        //Boolean - If there is a stroke on each bar
        barShowStroke: true,
        //Number - Pixel width of the bar stroke
        barStrokeWidth: 2,
        //Number - Spacing between each of the X value sets
        barValueSpacing: 5,
        //Number - Spacing between data sets within X values
        barDatasetSpacing: 1,
        multiTooltipTemplate: "<%=datasetLabel%>: <%= value + ' %' %>",
        //String - A legend template
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
        //Boolean - whether to make the chart responsive
        responsive: true,
        maintainAspectRatio: true
    };

    barChartOptions.datasetFill = false;
    barChart.Bar(barChartData, barChartOptions);

更新我把chart.js的最小版本改成了完整版本,这样我就可以看到它到底在哪里出错了。

这是来自chrome控制台

的图像

plicqrtu

plicqrtu1#

问题是,当你的代码执行时,画布还没有创建。你应该将你的代码 Package 在一个函数中,并将该函数分配给window.onload事件。你可以看到下面的示例代码。

window.onload = function() {
  var ctx = document.getElementById("myChart");
  var lineChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
      datasets: [{
        label: "2015",
        data: [10, 8, 6, 5, 12, 8, 16, 17, 6, 7, 6, 10]
      }]
    }
  })
}
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>

</head>

<body>
  <canvas id="myChart"></canvas>
</body>

</html>
0pizxfdo

0pizxfdo2#

找到了答案
必须首先解析 AJAX 结果。
结果定位

var barChartData = JSON.parse(d);
xvw2m8pv

xvw2m8pv3#

运行以下命令对我有效:

window.onload = function () {

}
zpjtge22

zpjtge224#

对于有此问题的其他用户,请确保在调用时存在容器canvas元素。

kjthegm6

kjthegm65#

您可以尝试将Chart.JS脚本标记和其他自定义JS脚本放在**<**/body>标记的末尾。

4si2a6ki

4si2a6ki6#

看起来你正在使用一个不存在的对象,至少我看不到它,datasets。我只能看到length在这个对象上被调用,除非有丢失的代码?
我可以看到您将d分配给barChartData

var barChartData = d;

因此,您可能希望将datasets的示例替换为barChartData

bcs8qyzn

bcs8qyzn7#

这是一个老问题,但是,我也有这个问题,在我的例子中,我的数据长度= 0。我解决了这个问题,只是在调用图之前添加了一个验证:

if (barChartData.length > 0)
{
   objChart = Morris.Bar({....
}
wwwo4jvm

wwwo4jvm8#

我在下载后遇到了同样的错误&使用ChartJS包使用免费的bootstrap 5管理模板。

Chart.min.js:7 Uncaught TypeError: Cannot read properties of null (reading 'length')
    at Object.acquireContext (Chart.min.js:7:76631)
    at ni.construct (Chart.min.js:7:92209)
    at new ni (Chart.min.js:7:91964)
    at chart-area-demo.js:7:19

在我的控制台中:

这是初始代码:

// Set new default font family and font color to mimic Bootstrap's default styling
Chart.defaults.global.defaultFontFamily = '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#292b2c';

// Area Chart Example
var ctx = document.getElementById("myAreaChart");
var myLineChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Mar 1", "Mar 2", "Mar 3", "Mar 4", "Mar 5", "Mar 6", "Mar 7", "Mar 8", "Mar 9", "Mar 10", "Mar 11", "Mar 12", "Mar 13"],
        datasets: [{
            label: "Sessions",
            lineTension: 0.3,
            backgroundColor: "rgba(2,117,216,0.2)",
            borderColor: "rgba(2,117,216,1)",
            pointRadius: 5,
            pointBackgroundColor: "rgba(2,117,216,1)",
            pointBorderColor: "rgba(255,255,255,0.8)",
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(2,117,216,1)",
            pointHitRadius: 50,
            pointBorderWidth: 2,
            data: [10000, 30162, 26263, 18394, 18287, 28682, 31274, 33259, 25849, 24159, 32651, 31984, 38451],
        }],
    },
    options: {
        scales: {
            xAxes: [{
                time: {
                    unit: 'date'
                },
                gridLines: {
                    display: false
                },
                ticks: {
                    maxTicksLimit: 7
                }
            }],
            yAxes: [{
                ticks: {
                    min: 0,
                    max: 40000,
                    maxTicksLimit: 5
                },
                gridLines: {
                    color: "rgba(0, 0, 0, .125)",
                }
            }],
        },
        legend: {
            display: false
        }
    }
});

因此,我所做的就是通过使用条件(IF)添加一个简单的存在性验证。像这样:

// Set new default font family and font color to mimic Bootstrap's default styling
Chart.defaults.global.defaultFontFamily = '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#292b2c';

// Area Chart Example
var ctx = document.getElementById("myAreaChart");
if (ctx) {
    var myLineChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ["Mar 1", "Mar 2", "Mar 3", "Mar 4", "Mar 5", "Mar 6", "Mar 7", "Mar 8", "Mar 9", "Mar 10", "Mar 11", "Mar 12", "Mar 13"],
            datasets: [{
                label: "Sessions",
                lineTension: 0.3,
                backgroundColor: "rgba(2,117,216,0.2)",
                borderColor: "rgba(2,117,216,1)",
                pointRadius: 5,
                pointBackgroundColor: "rgba(2,117,216,1)",
                pointBorderColor: "rgba(255,255,255,0.8)",
                pointHoverRadius: 5,
                pointHoverBackgroundColor: "rgba(2,117,216,1)",
                pointHitRadius: 50,
                pointBorderWidth: 2,
                data: [10000, 30162, 26263, 18394, 18287, 28682, 31274, 33259, 25849, 24159, 32651, 31984, 38451],
            }],
        },
        options: {
            scales: {
                xAxes: [{
                    time: {
                        unit: 'date'
                    },
                    gridLines: {
                        display: false
                    },
                    ticks: {
                        maxTicksLimit: 7
                    }
                }],
                yAxes: [{
                    ticks: {
                        min: 0,
                        max: 40000,
                        maxTicksLimit: 5
                    },
                    gridLines: {
                        color: "rgba(0, 0, 0, .125)",
                    }
                }],
            },
            legend: {
                display: false
            }
        }
    });
}

在那之后没有更多的错误。

相关问题