我一直在寻找与 chart.js
相关的问题,但似乎没有两个开发人员对如何使用 chart.js
+ JSON 显示图表给出相同的答案。
我正在尝试使用 JSON 文件显示图表 - 特别是“数量”列表及其相关标签(“2017 年 1 月”,...)。
图表 Canvas 显示正常,没有控制台日志错误,但没有图表本身。我错过了什么?
谢谢!
这是我的 chart.js 代码:-
var labels = [];
var data = [];
$.getJSON("https://jsonblob.com/api/jsonBlob/26078b70-6b6f-11e7-a38a-bf689f57642c"), function (data) {
$.each(data.customers.amounts, function(key, value){
var labels = json.map(function(item) {
labels.push(item.key);
});
var data = json.map(function(item) {
data.push(item.value);
});
});
}
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
labels: labels,
backgroundColor: 'rgb(129, 198, 2228)',
borderColor: 'rgb(0, 150, 215)',
data: data
}]
},
options: {
responsive: 'true',
}
});
这是我的 JSON 文件:-
{
"customers": [
{
"first_name": "John",
"last_name": "Doe",
"account": "123456",
"period": "13th July - 13th August",
"due_date": "14th September",
"amounts": [
["January 2017", 121.23],
["February 2017", 145.23],
["March 2017", 55.12],
["April 2017", 78.58],
["May 2017", 89.13],
["June 2017", 45.78],
["July 2017", 90.22]
]
}
]
}
最佳答案
几个问题:
- 自
$.getJSON()
方法是异步的,您应该在它的回调函数中构建图表。 - 您错误地循环了响应数据。可以简单到:
var labels = data.customers[0].amounts.map(function(e) {
return e[0];
});
var data = data.customers[0].amounts.map(function(e) {
return e[1];
});
- 您正在向数据集添加
labels
数组,而它属于data
对象。<
这是您的代码的修订版:
$.getJSON("https://jsonblob.com/api/jsonBlob/26078b70-6b6f-11e7-a38a-bf689f57642c", function(data) {
var labels = data.customers[0].amounts.map(function(e) {
return e[0];
});
var data = data.customers[0].amounts.map(function(e) {
return e[1];
});
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
backgroundColor: 'rgb(129, 198, 2228)',
borderColor: 'rgb(0, 150, 215)',
data: data
}]
},
options: {
responsive: 'true',
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>
关于javascript - 在 chart.js 中使用 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45273313/