我使用的是服务器发送事件(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).
我希望他只更新同一行;
我的完整代码:
**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();
}
?>
您可以执行:
test.php-将您的echo替换为:
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>