gpt4 book ai didi

javascript - 使用 css 创建一个框以显示来自事件源的数据

转载 作者:行者123 更新时间:2023-11-28 02:55:26 24 4
gpt4 key购买 nike

我想创建一个框来使用 css 显示来自事件源的数据。例如, enter image description here

在这张图片中,我想创建一个框来从 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>

我的输出是这样的 enter image description here

输出是它们在底部显示数据。这不是我想要的..关于如何做到这一点的任何想法..

我的问题是如何创建一个盒子来观察数据。随着脚本的更新,旧数据会下降。在第四行之后你什么也看不到。新数据将出现在顶部。你能帮我么。谢谢..

最佳答案

您可以使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com