简体   繁体   English

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

[英]Chart Js Cannot read property 'length' of undefined

Using Chart js I am trying to pull data from Ajax call to supply to the Chart.使用 Chart js 我试图从 Ajax 调用中提取数据以提供给图表。 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目前这是我在下面的内容,我得到的错误是

在此处输入图片说明

$(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.下面的代码正在获取 Ajax get 请求的结果(我是通过将它转储到控制台获得的)并创建相同内容的“硬编码”版本。 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.唯一应该在技术上有所不同的是,在页面加载时加载数据,然后在非常短暂的时间内加载数据。

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

Update I 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这是来自 chrome 控制台的图像在此处输入图片说明

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.您应该将代码包装在一个函数中,并将该函数分配给 window.onload 事件。 You can see the sample code below.您可以查看下面的示例代码。

 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>

Found the answer,找到了答案,

The Ajax results has to be parsed first.必须首先解析 Ajax 结果。

resulting fix结果修复

var barChartData = JSON.parse(d);

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

running the following worked for me:运行以下对我有用:

window.onload = function () {

}

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

It looks like you're using an object that doesn't exist, well at least I cant see it, datasets .看起来您正在使用一个不存在的对象,至少我看不到它, datasets I can only see length being called on this object, unless there's missing code?除非缺少代码,否则我只能看到对该对象调用的length

I can see you assign d to barChartData我可以看到你将d分配给barChartData

var barChartData = d;

So, you might want to replace the instances of datasets with barChartData .因此,您可能希望用barChartData替换datasets的实例。

It's an old question but, I had this issue as well and in my case my data was length = 0. I solved this just adding a validation before calling the the graph:这是一个老问题,但是,我也有这个问题,在我的情况下,我的数据长度 = 0。我解决了这个问题,只是在调用图表之前添加了验证:

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

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

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