图表;无法读取未定义的属性“0"

2022-01-22 00:00:00 javascript ajax chart.js

我想做的是使用 chartjs 创建条形图.数据通过 $.ajax 检索.从 $.ajax 检索到的 JSON 数据稍后将添加到数据集.但是,当我要创建一个chartjs 时.Chart.js 库出现错误:

Uncaught TypeError: Cannot read property '0' of undefined

我在加载完ajax后检查了所有数据.JSON没有问题(我已经检查了控制台).此外,当我检查 myBarChart 类型报告为未定义.甚至在我完成检索 JSON 数据后,我已经为自己分配了一个新的 chartjs.

这是一段 JavaScript 代码:

var driverCode, driverPointsGained = "";var exLabel = new Array();var exPoints = new Array();var 图表数据;var myBarChart;var ctx = document.getElementById("driverStandingChart").getContext("2d");//var ctx = $("#driverStandingChart").get(0).getContext("2d");Chart.defaults.global.responsive = true;函数addChartData(代号,积分){图表数据 = {标签:代号,数据集:[{填充颜​​色:rgba(151,187,205,0.5)",strokeColor: "rgba(151,187,205,0.8)",highlightFill: "rgba(151,187,205,0.75)",highlightStroke: "rgba(151,187,205,1)",数据:积分}]};返回图表数据;}$("#testAjaxLoading").click(函数 (e) {e.preventDefault();$.ajax({网址:http://ergast.com/api/f1/current/driverStandings.json",数据类型:json",成功:函数(数据){控制台信息(数据);for (var i = 0; i <= data.MRData.total-1; i++) {driverCode = data.MRData.StandingsTable.StandingsLists[0].DriverStandings[i].Driver.code;driverPointsGained = data.MRData.StandingsTable.StandingsLists[0].DriverStandings[i].points;console.info("code:" + driverCode +" points:" + driverPointsGained);//将数据推入数组exLabel.push(driverCode);exPoints.push(driverPointsGained);}addChartData(exLabel,exPoints);console.log(chartData);myBarChart = new Chart(ctx).Bar(chartData);alert("完成检索数据");},错误:函数(错误){控制台.错误(错误);}});});

带有 HTML 的完整代码:

如果不是这样,那么 ChartJS 在您的 JSON 中寻找的元素是未定义的.如果是这种情况,您必须查看文档以查看缺少哪个元素.

What I'm trying to do is use chartjs to create a Bar chart. The data is retrieved via $.ajax. And JSON data retrieved from $.ajax will be added later to dataset. However, when I'm about to create a chartjs. There is an error from Chart.js library:

Uncaught TypeError: Cannot read property '0' of undefined 

I have checked all the data after finished loading the ajax .There is no problem with the JSON (I've already check the console). Moreover, when I checked the myBarChart type is reported as undefined. Even I already assigned a new chartjs to itself after I finished retrive JSON data.

Here is a JavaScript Code:

var driverCode, driverPointsGained = "";
var exLabel = new Array();
var exPoints = new Array();
var chartData;
var myBarChart;
var ctx = document.getElementById("driverStandingChart").getContext("2d");
//var ctx = $("#driverStandingChart").get(0).getContext("2d");

Chart.defaults.global.responsive = true;

function addChartData(codename, pointsgained) {
    chartData = {
        label: codename,
        datasets: [
            {
                fillColor: "rgba(151,187,205,0.5)",
                strokeColor: "rgba(151,187,205,0.8)",
                highlightFill: "rgba(151,187,205,0.75)",
                highlightStroke: "rgba(151,187,205,1)",
                data: pointsgained
            }
        ]
    };
    return chartData;
}

$("#testAjaxLoading").click(function (e) {
    e.preventDefault();
    $.ajax({
        url: "http://ergast.com/api/f1/current/driverStandings.json",
        dataType: "json",
        success: function (data) {
            console.info(data);

            for (var i = 0; i <= data.MRData.total-1; i++) {

                driverCode = data.MRData.StandingsTable.StandingsLists[0].DriverStandings[i].Driver.code;
                driverPointsGained = data.MRData.StandingsTable.StandingsLists[0].DriverStandings[i].points;

                console.info("code: " + driverCode + " points: " + driverPointsGained);

                //push data to array
                exLabel.push(driverCode);
                exPoints.push(driverPointsGained);
            }

            addChartData(exLabel,exPoints);

            console.log(chartData);

            myBarChart = new Chart(ctx).Bar(chartData);

            alert("finished retrieve data");
        },
        error: function (err) {
            console.error(err);
        }
    });
});

Full code with HTML: https://gist.github.com/sancowinx/31b6289b7f28908db0c1

For the JSON data, I use an API from Ergast API to get a JSON Results.

edit: adding Stack Trace:

$.ajax.success is actually myBarChart = new Chart(ctx).Bar(chartData);

Any suggestions? Thanks in advance.

解决方案

Your stack trace tells me that either ctx or chartData is undefined. My guess is that it's ctx if you've already checked chartData. (Verify this using console.log.) Perhaps this is the answer if that's the case: canvas.getContext("2d") is undefined

If that's not the case, then an element that ChartJS was looking for in your JSON was undefined. You'll have to look through the documentation to see what element is missing if that's the case.

相关文章