我想创建一个框,以使用css显示事件源中的数据。
例如,
在这张照片中,我想创建一个框来从php脚本加载数据。新数据将显示在顶部。我想在顶部看到新数据。随着新数据的更新,旧数据下降,并且在4行之后您看不到旧数据。我使用CSS来实现它。我使用溢出来隐藏旧数据。相反,新数据位于底部。请帮我。谢谢。
我的代码在下面
PHP脚本
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "netwitness";
$dbname = "abdpractice";
$con = mysqli_connect ($dbhost, $dbusername, $dbpassword) or die ('Error in connecting: ' . mysqli_error($con));
//Select the particular database and link to the connection
$db_selected = mysqli_select_db($con, $dbname ) or die('Select dbase error '. mysqli_error());
//Make A SQL Query and link to the connection
$result = mysqli_query($con,"SELECT * FROM `countryattack` ORDER BY RAND() LIMIT 1");
while ($row = mysqli_fetch_assoc($result))
{
echo "data: [X] NEW ATTACK: FROM " . $row["countrysrc"]. " TO " . $row["countrydst"]. " \n\n";
}
mysqli_close($con);
?>
HTML代码
<!DOCTYPE html>
<html>
<head>
<style>
div.hidden {
background-color: #00FF00;
width: 500px;
height: 100px;
overflow: hidden;
}
</style>
</head>
<body>
<h1>Getting server updates</h1>
<div class="hidden" id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("shownewattack.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
我的输出是这样的
输出是它们在底部显示数据。这不是我想要的。有关此操作的任何想法。
我的问题是如何创建一个观察数据的盒子。随着脚本的更新,旧数据将下降。在第四行之后,您什么都看不到。新数据将出现在顶部。你能帮我么。谢谢..
最佳答案
您可以使用Node.insertBefore()
代替串联父元素的.innerHTML
。
const result = document.getElementById("result");
source.onmessage = function(event) {
const node = document.createTextNode(event.data + "\n");
if (!result.firstChild) {
result.appendChild(node);
else {
result.insertBefore(node, result.firstChild);
}
};
<pre id="result"></pre>
<script>
const result = document.getElementById("result");
let n = 0;
const interval = setInterval(() => {
let node = document.createTextNode(++n + "\n");
if (!result.firstChild) {
result.appendChild(node);
} else {
result.insertBefore(node, result.firstChild)
}
}, 500);
</script>
关于javascript - 创建一个框以使用CSS显示事件源中的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46480413/