Javascript Ajax为JSON增加了价值,使其每秒都能被绘制成图形
我有一个Arduino,通过以太网屏蔽,每秒通过AJAX打印一个值。我想用图形表示这个值。这需要将值放在JSON格式中,如下所示Javascript Ajax为JSON增加了价值,使其每秒都能被绘制成图形,javascript,php,ajax,json,flot,Javascript,Php,Ajax,Json,Flot,我有一个Arduino,通过以太网屏蔽,每秒通过AJAX打印一个值。我想用图形表示这个值。这需要将值放在JSON格式中,如下所示 [[epochtimestamp, value], [epochtimestamp, value]] 因此,我想知道您是否可以帮助我使用JavaScript/AJAX(或者PHP,如果您认为合适的话)每秒获取这个值,并将其添加到.txt文件(用于存储以前的值)中的JSON中,这样Flot就可以读取所有值并创建这些值的基于时间的图形,但每秒都可以通过AJAX更新图形
[[epochtimestamp, value], [epochtimestamp, value]]
因此,我想知道您是否可以帮助我使用JavaScript/AJAX(或者PHP,如果您认为合适的话)每秒获取这个值,并将其添加到.txt文件(用于存储以前的值)中的JSON中,这样Flot就可以读取所有值并创建这些值的基于时间的图形,但每秒都可以通过AJAX更新图形
这是每秒钟都需要进行的基本过程
<?php
$file = 'data.txt';
$webpage = 'test.txt';
$t = time(); // Open the file to get existing content
$current = file_get_contents($file);
$data = file_get_contents($webpage);
// Append a new person to the file
if ($current < 1) {
$current .= "[[" + $t + "," + $data + "]";
} else {
$current .= ", " + "[" + $t + "," + $data + "]";
} // Write the contents back to the file
file_put_contents($file, $current);
echo $current;
?>
我不确定使用Javascript/AJAX是否更容易?看看flot的源代码 您可以从浏览器通过AJAX调用PHP脚本,您的客户端代码应该如下所示
// Initialize your empty plot
var plot = $.plot("#myPlot", [], {
series: {
shadowSize: 0 // Drawing is faster without shadows
},
yaxis: {
min: 0,
max: 100
},
xaxis: {
show: false
}
});
function update() {
// Make an ajax call to your script to get data provided by your script
// Which reads that data.txt from Arduino.
$.ajax({
url: "yourhost/yourscript.php",
context: document.body
}).done(function(response) {
// Get the ajax response
data = response;
// If data is not null, set your plot's data.
if (data != null)
plot.setData(data);
// Draw the plot.
plot.draw();
// Re-invoke update.
update();
});
}
// Initial call to the update func.
update();
如果您使用了一些代码,请您发布一些代码,好吗?我开始使用PHP将其添加到文件等,但它必须每秒由AJAX调用。我也15岁了,正在努力学习,所以任何对我有帮助的建议或评论都非常感谢。嗯,这似乎不起作用。我必须将null更改为0,否则它会出错。但是现在函数getData()只返回0。在函数getData()中,我放置document.write(data);它打印出了所有的值。因此,它不会返回在函数外部使用的值?这不应该是您正在处理的确切代码,关键是使用ajax获取数据,并使用flot显示数据。继续工作,我一有时间就会做一个样本:)这个代码是错误的<代码>$.ajax({是异步的。
setData
和plot.draw
需要发生在它的done处理程序中。这种编码方式getData将始终返回null
。哦,我的天啊,这是一个多么愚蠢的错误。谢谢@Mark。我已经更新了我的答案,但没有时间尝试它,你现在可以再次检查吗?我尝试了,但它不起作用。它不会绘制他在没有轴和数据点的情况下绘图..?而且上面的代码中缺少setTimeout,所以我不得不把它放回去。我知道AJAX每秒都在调用PHP文件,Flot只是没有绘制它?