我想使用json数据绘制chart.js,我用getjson查询。
下面的代码给我和空图。但是,如果我使用alert(ddata.length)取消注释该行;不仅它会弹出一个0,但这次的情节正确 - 混乱的行为。使用chart.js 2.6.0 jquery 3.3.1。
var ddata = [];
//var labels = [];
$.getJSON("http://192.168.1.143/json_request", function(jdata){
$.each(jdata, function(i, d){
ddata.push({"x":d.timestamp, "y": d.x0});
//labels.push(String(d.timestamp));
});
});
//alert(ddata.length); // <-- Works if uncommented !!!
//console.table(ddata);
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
//labels: labels,
datasets: [{
label: 'h1px2',
data: ddata,
backgroundColor: 'rgba(0, 0, 255, 0.2)',
borderColor: 'rgba(0,0,255,1)',
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
type: 'linear'
}]
}
}
});
json的样本:
[{"timestamp": 1528828783,"x0": 246.21,"x1": 1.16,"x2": 11.47,"x3": 8.62,"x4": -127.00},
{"timestamp": 1528828793,"x0": 245.75,"x1": 1.37,"x2": 15.41,"x3": 4.93,"x4": -127.00}, etc...
你能告诉我如何才能正确地绘制这些图片吗?