【发布时间】:2014-09-29 19:47:07
【问题描述】:
我想做的是使用 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 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);
}
});
});
带有 HTML 的完整代码:https://gist.github.com/sancowinx/31b6289b7f28908db0c1
对于 JSON 数据,我使用来自 Ergast API 的 API 来获取 JSON 结果。
编辑:添加堆栈跟踪:
$.ajax.success 其实是myBarChart = new Chart(ctx).Bar(chartData);
有什么建议吗?提前致谢。
【问题讨论】:
-
如果没有
f1.js文件依赖项,就无法运行您的示例。 :// -
另外,如果您粘贴错误的堆栈跟踪会容易得多:developer.chrome.com/devtools/docs/…
-
@CullenJ 添加了堆栈跟踪。实际上对于 f1.js 和这个问题不太相关。 f1.js 用于检索其他结果。不过可以找f1.js源码here
标签: javascript ajax chart.js