Javascript 如何绘制json数据
我每4秒会得到一个json数据,如下所示:Javascript 如何绘制json数据,javascript,jquery,flot,flotr,flotr2,Javascript,Jquery,Flot,Flotr,Flotr2,我每4秒会得到一个json数据,如下所示: { "time": "04:49:07 AM", "milliseconds_since_epoch": 1375246147254, "date": "07-31-2013" } 我处理它是为了得到这样一个数组: { "time": "04:49:07 AM", "milliseconds_since_epoch": 1375246147254, "date": "07-31-2013" } [13752306
{
"time": "04:49:07 AM",
"milliseconds_since_epoch": 1375246147254,
"date": "07-31-2013"
}
我处理它是为了得到这样一个数组:
{
"time": "04:49:07 AM",
"milliseconds_since_epoch": 1375246147254,
"date": "07-31-2013"
}
[1375230673948,0.6443498175195954]]
(第一个数据是js时间戳)
我试图使用flot实时绘制这些数据:
function draw() {
console.log('draw called');
this.array = getTimeArray();
$.plot(
$("#placeholder"), [
{
label: "test Data",
data: this.array,
lines: {
show: true,
fill: true,
fillColor: "rgba(249, 28, 61,0.3)",
lineWidth: 2.5
},
}
], {
xaxis: {
mode: "time",
timeformat: "%H:%M"
},
yaxis: {
min: -2
}
});
}
function getTimeArray(flg) {
var array = [],
d = new Date(),
tz = d.getTimezoneOffset();
jsonUrl = 'http://date.jsontest.com/'
var array2 = []
$.getJSON(jsonUrl, function(data) {
var i = 0;
$.each(data, function(key, val) {
if (typeof val === 'number'){
d = new Date(val - 5 * 60 * 1000);
array2.push([d.getTime()- tz*60*1000,Math.random()]);
console.log(array2)
i++;
}
});
});
for (var i = 9; i >= 0; i--) {
d = new Date(d.getTime() - 5 * 60 * 1000);
array.push([d.getTime() - tz*60*1000, Math.random()]);
}
return array;
}
draw();
setInterval(draw, 4000);
但我还没拿到,有人能帮我吗
我需要用它们的值绘制时间序列,从中获取数据
json。也许使用另一个库可以更容易地访问它,欢迎任何帮助。您的代码的问题是,
$.getJSON
调用是异步的,因此如果您尝试返回array2
(在jsFiddle中),它是一个空列表。从服务器获取JSON数据后,需要使用success
回调或.done()
方法绘制绘图:
$.getJSON(jsonUrl, function (jdata) {
var i = 0;
$.each(jdata, function (key, val) {
if (typeof val === 'number') {
d = new Date(val - 5 * 60 * 1000);
if (array.length > 9) {
array.shift();
}
array.push([d.getTime() - tz * 60 * 1000, Math.random()]);
i++;
}
});
}).done(function (jdata) {
data[0]["data"] = array;
$.plot($("#placeholder"), data, options);
});
你可以看到这张照片。我不断地推动数组,当它的长度超过9时移动它,只是为了举例说明
您也可以使用flot绘图的setData
和draw
方法来避免每次绘制绘图,但这是一个不同的问题