SSE - (发送服务器事件)

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

我使用的是server-sent-events(SSE),我想让他更新同一行,而不是用同样的数据再创建一行,比如:我是要求SSE实时更新数据(JSON),但它没有更新数据,而是在下面一行发送同样的数据。

**JSON (example):**

{"user": "John", "message": "First line"}

He returns me every 3 seconds:
user: John - message: first line
user: John - message: first line
user: John - message: first line
user: John - message: first line
(and so on, in an infinite loop).

我希望他只是更新同一行数据。

我的COMPLETE CODE。

  • Front
**This code requests the SSE**
<html lang="en">
<head>
<title>Using Server-Sent Events</title>
<script>
    var source = new EventSource("test.php");
    source.onmessage = function(event) {
        var jdata = JSON.parse(event.data);
        document.getElementById("result").innerHTML += "" + event.data + "<br>";
    };
</script>
</head>
<body>
    <div id="result">
        <!--Server response will be inserted here-->
    </div>
</body>
</html>

  • 返回
**This code responds with JSON**
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

            $curl = curl_init();
            curl_setopt_array($curl, array(
              CURLOPT_URL => "https://api.chat-api.com/instance****/messages?token=*****&chatId=*****%40c.us",
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => "",
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 0,
              CURLOPT_FOLLOWLOCATION => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => "GET",
              CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json"
              ),
            ));
            $response = curl_exec($curl);
            curl_close($curl);
            $array = json_decode($response);

            foreach ($array->messages as $value) {
              $data = json_encode($value->body);
              echo "data: {$data}\n\n";
              flush();
            }


?>
javascript php json server-sent-events
1个回答
0
投票

你可以用:

test.php -用...代替你的回音

echo "<p id='dataresult'>data: {$data}\n\n</p>";

而在你的 js脚本 :

  **This code requests the SSE**
<html lang="en">
<head>
<title>Using Server-Sent Events</title>
<script>
    var source = new EventSource("test.php");
    source.onmessage = function(event) {
        var jdata = JSON.parse(event.data);
        document.getElementById("result").innerHTML = "" + event.data + "<br>";
    };
</script>
</head>
<body>
    <div id="result">
        <!--Server response will be inserted here-->
    </div>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.