我通过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个值)。
然而,我得到: -
未捕获的TypeError:无法读取null的属性'length'
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)
答案 0 :(得分:0)
我在Chart.js库中使用了cdn,在下载库并将其放入我的项目时,它以某种方式解决了问题......