如何在同一位置刷新div,避免重复行

问题描述 投票:0回答:1

需要使用来自服务器的数据刷新div。服务器正在使用服务器发送事件发送数据。

一切正常,但数据以新行显示。我需要在相同的位置刷新相同的div,而不是添加更多的行。

这是html页面:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>

        <div id="result">Loading data. Please, wait...</div>

        <script type="text/javascript">
            if(typeof(EventSource) !== "undefined") {
                var source = new EventSource("demo_sse.php");

                source.addEventListener('message', function(e) {
                    document.getElementById("result").innerHTML += event.data + "<br>";
                }, false);

                source.addEventListener('open', function(e) {
                    // Connection was opened.
                    //alert('Connection opened');
                }, false);

                source.addEventListener('close', function(e) {
                    // Connection was opened.
                    alert('Connection closed');
                }, false);

                source.addEventListener('error', function(e) {
                    if (e.readyState == EventSource.CLOSED) {
                    // Connection was closed.
                        alert('Connection closed');
                    }
                }, false);

            } else {
                document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
            }
        </script>
    </body>
</html>

这是php文件:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "retry: 1000\n";
echo "data: The server time is: {$time}\n\n";
//error_log('XXXX');
flush();
?>
javascript html5 server-sent-events
1个回答
0
投票

将行更改为:

source.addEventListener('message', function(e) {
                    document.getElementById("result").innerHTML = event.data + "<br>";
                }, false);
© www.soinside.com 2019 - 2024. All rights reserved.