我有以下代码从数据库获取值并执行简单的折线图(对警报的响应时间与UTC时间).它在静态时可以完美工作,但是现在我想“实时”获取数据(只是进行测试,例如每2秒获取每个元素,即2000毫秒).以下是以静态方式工作的代码:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM data";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>User</th><th>Zulu</th><th>Server Time</th><th>Sample</th><th>Response Time</th></tr>";
// output data of each row
$dataset1 = array();
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row[""]. "</td><td>" . $row[""]. "</td><td>" . $row[""]. "</td><td>" . $row[""]. "</td><td>" . $row[""]. "</td></tr>";
$dataset1[] = array(floatval($row[""]),intval($row[""]));
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
如我们所见,数据存储在$dataset1变量中,然后我有一个简单的脚本对其进行绘制:
<script>
//put array into javascript variable
var dataset1 = <?php echo json_encode($dataset1); ?>;
var data = [
{
data: dataset1,
}
];
var options = {
};
$(function () {
$.plot($("#placeholder"), data,options);
});
</script>
我的问题是:我如何用这个$dataset1“玩具”每2000 ms绘制一次?
这就是我得到的:
解决方法:
如果每2秒需要一次,则应使用.setTimeout(),因为.setInterval()可能不准确.
您可能需要tweek这样才能使值保留在每次调用getData函数时.最好的方法是将它们存储在传递给函数的元素中.
如果您希望我对此进行测试并为其创建JS FIDDLE,则需要发布HTML代码.
(function($){
$(function(){ //document.ready
});
(function getData(element){
var xval = xval ? xval : 0;
var yVal1 = Math.floor(Math.random()*11);
var yVal2 = Math.floor(Math.random()*11);
var datum1 = [xVal, yVal1];
var datum2 = [xVal, yVal2];
var data = data ? data : [[],[]];
var plot = $.plot(element, data);
data[0].push(datum1);
data[1].push(datum2);
if(data[0].length>10){
data[0] = data[0].splice(1);
data[1] = data[1].splice(1);
}
xVal++;
plot.setData(data);
plot.setupGrid();
plot.draw();
}
setTimeout(function(){
getData(element);
}, 2000);
})($('#chart4'));
})(jQuery);