I'm using server-sent-events (SSE), I wanted it to update the same line, instead of creating another one with the same data, for example: I am requesting SSE to update the data in real time (JSON), but instead of updating the data, it sends the same data on the line below;
**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).
I wanted him to just update the same line;
MY COMPLETE CODE:
**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();
}
?>
You can do:
test.php - Replace your echo by:
echo "<p id='dataresult'>data: {$data}\n\n</p>";
And in your js script :
**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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.