使用来自服务器的数据绘制 chart.js
Draw chart.js with data from server
我知道我一定犯了一个基本错误,但我是新手。我想用来自服务器的数据在我的视图中填充折线图 (chart.js)。我已经确认在视图中收到了数据,但我怀疑它的格式有误。
我的控制器:
public ActionResult GetLineChartData()
{
var data = new
{
title = "test_data",
data = new[] {
new { value = "V1", key = "11"},
new{ value = "V2", key = "10"}
}
};
return Json(data, JsonRequestBehavior.AllowGet);
}
我的看法:
<canvas id="lineChart" width="400" height="400"></canvas>
<button id="lineChartUpdate">Update Chart</button>
<script>
$(document).ready(function () {
$("#lineChartUpdate").click(function () {
$.ajax({
type: "Post",
url: '@Url.Action("GetLineChartData", "Posts")',
data: {},
dataType: "json",
traditional: true,
success: function (data) {
new Chart('lineChart', {
type: 'line',
data: {
labels: data.data.map(a => a[0]),
datasets: [{
label: 'My Dataset',
data: data.data.map(a => a[1]),
fill: false,
borderColor: 'red'
}]
},
options: {
scales: {yAxes: [{ ticks: { beginAtZero: true } }]}
}
});
}
});
});
});
</script>
我收到此错误:“标尺的标尺配置无效:yAxes”
这是因为如错误所述,它是无效的,您正在将 V2 配置与 V3 一起使用。
在 V3 中,所有比例在比例对象中都有自己的对象,而不是 2 个数组。
更改为:
scales: {
y: {
// Scale config
}
}
将删除警告并使配置正确应用
对于 V2 和 V3 之间的所有变化,请阅读 migration guide
我知道我一定犯了一个基本错误,但我是新手。我想用来自服务器的数据在我的视图中填充折线图 (chart.js)。我已经确认在视图中收到了数据,但我怀疑它的格式有误。
我的控制器:
public ActionResult GetLineChartData()
{
var data = new
{
title = "test_data",
data = new[] {
new { value = "V1", key = "11"},
new{ value = "V2", key = "10"}
}
};
return Json(data, JsonRequestBehavior.AllowGet);
}
我的看法:
<canvas id="lineChart" width="400" height="400"></canvas>
<button id="lineChartUpdate">Update Chart</button>
<script>
$(document).ready(function () {
$("#lineChartUpdate").click(function () {
$.ajax({
type: "Post",
url: '@Url.Action("GetLineChartData", "Posts")',
data: {},
dataType: "json",
traditional: true,
success: function (data) {
new Chart('lineChart', {
type: 'line',
data: {
labels: data.data.map(a => a[0]),
datasets: [{
label: 'My Dataset',
data: data.data.map(a => a[1]),
fill: false,
borderColor: 'red'
}]
},
options: {
scales: {yAxes: [{ ticks: { beginAtZero: true } }]}
}
});
}
});
});
});
</script>
我收到此错误:“标尺的标尺配置无效:yAxes”
这是因为如错误所述,它是无效的,您正在将 V2 配置与 V3 一起使用。
在 V3 中,所有比例在比例对象中都有自己的对象,而不是 2 个数组。
更改为:
scales: {
y: {
// Scale config
}
}
将删除警告并使配置正确应用
对于 V2 和 V3 之间的所有变化,请阅读 migration guide