我正在通过 ajax 调用使用
Chart.js
$.ajax({
url: 'MenuG.aspx/GetGraphData',
type: "POST",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: loadChart,
error: function (xhr, status, error) {
alert("קרתה שגיאה בטעינת הגרף");
}
});
function loadChart(jsonData) {
var data = jsonData.d;
if (data != undefined && data != null) {
if (data.Col1 != null && data.Col2 != null && data.Col3 != null && data.Col4 != null) {
var labelsToDisplay = [data.Col1.Desc, data.Col2.Desc, data.Col3.Desc, data.Col4.Desc];
var dataTotal = [parseInt(data.Col1.total), parseInt(data.Col2.total), parseInt(data.Col3.total), parseInt(data.Col4.total)];
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: labelsToDisplay,
datasets: [
{
//label: "Population (millions)",
backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9"],
data: dataTotal
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: jsonData.GraphName
},
animation: { // show each column total on top
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.fillStyle = "black";
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
for (var key in dataset._meta) {
var model = dataset._meta[key].data[i]._model;
ctx.fillText(dataset.data[i], model.x, model.y - 5);
}
}
});
}
}
}
}); //Chart
}//if
}// if
} //loadChart
我创建了 2 个数组
labelsToDisplay
用于条形标签,dataTotal
用于条形值(我检查过,它们都有 4 个值)。
但是,我得到:-
未捕获类型错误:无法读取 null 的属性“长度”
Uncaught TypeError: Cannot read property 'length' of null
at Object.acquireContext (Chart.min.js:13)
at t.construct (Chart.min.js:11)
at new t (Chart.min.js:12)
at Object.loadChart [as success] (MenuG.aspx?param=1:66)
at j (jquery.js:3148)
at Object.fireWith [as resolveWith] (jquery.js:3260)
at x (jquery.js:9314)
at XMLHttpRequest.b (jquery.js:9718)
我正在使用 Chart.js 库的 CDN,当下载该库并将其放入我的项目时,它以某种方式解决了问题......