Javascript 图表 Js 无法读取未定义的属性“长度”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36650455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:22:06  来源:igfitidea点击:

Chart Js Cannot read property 'length' of undefined

javascriptjquerychart.js

提问by scripter78

Using Chart js I am trying to pull data from Ajax call to supply to the Chart. I found a few other postings where people have suggested delaying the canvas load but nothing has seemed to work. Currently this is the what I have below and the error that I get is

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

enter image description here

在此处输入图片说明

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


        }
    });
    }
});

UPDATE HERE SHOWING HOW NON AJAX WORKS

此处更新显示非 AJAX 的工作原理

The below code is taking the results of the Ajax get request (which I got from dumping it to the console) and creating a "hard coded" version of the same thing. The only thing that should technically be different is one has the data loaded at time of the page and the second the data is loaded very briefly after.

下面的代码正在获取 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);

UpdateI changed from the min version of chart.js to the full version so I could see where exactly it was erroring out at.

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

Here is the image from chrome console enter image description here

这是来自 chrome 控制台的图像 在此处输入图片说明

采纳答案by scripter78

Found the answer,

找到了答案,

The Ajax results has to be parsed first.

必须首先解析 Ajax 结果。

resulting fix

结果修复

var barChartData = JSON.parse(d);

回答by Omid Sadeghi

The problem is that when your code executes, the canvas has not been created yet. You should wrap your code inside a function and assign that function to window.onload event. You can see the sample code below.

问题是当你的代码执行时,画布还没有被创建。您应该将代码包装在一个函数中,并将该函数分配给 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>

回答by Himant

You may try putting the Chart.JS script tag and other custom JS scripts just before the end of **<**/body>tag.

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

回答by Kenneth Chang

running the following worked for me:

运行以下对我有用:

window.onload = function () {

}

回答by Mohsen.Sharify

For other users who have this problem, make sure your container canvas element exists, when called upon.

对于遇到此问题的其他用户,请确保在调用时您的容器画布元素存在。

回答by christiandev

It looks like you're using an object that doesn't exist, well at least I cant see it, datasets. I can only see lengthbeing called on this object, unless there's missing code?

看起来您正在使用一个不存在的对象,至少我看不到它,datasets。我只能看到length在这个对象上被调用,除非缺少代码?

I can see you assign dto barChartData

我可以看到你分配dbarChartData

var barChartData = d;

So, you might want to replace the instances of datasetswith barChartData.

所以,你可能要替换的实例datasetsbarChartData