简体   繁体   中英

html5 - Server side events: Replace line instead of append

I am aiming at using HTML5 SSE (Server Side Events) to send updates of data from server to the client. Currently the time is appended as an extra line. I am using the [\\n\\n] in the php-file in order to stop the stream.

Question: How can I replace the complete line insted of having it appended? I want the replacement to be in the same place, thus be kept inside the div [result].

I have tried to remove the br-tag at line 17 of the html-file, but it did not remove the "newline".

My html5 file, with js included:

  <h1>SSE test</h1>
  <div id="result"></div>

  <script>
      // Create an object
      var source = new EventSource("updater.php");
      // Detect message receipt
      source.onmessage = function(event) {
          // Write the received data to the page
          document.getElementById("result").innerHTML += event.data + "<br>";
      };
  </script>

my php file:

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

// The server time
  $time = date('r');
  echo "data: The server time is: {$time}\n\n";

flush();
?>

In your source.onmessage callback, just change the line to this:

document.getElementById("result").innerHTML = event.data + "<br>";

The problem is caused by the += operator, which appends the new result to the previous one. Now, with = it overwrites the old result, thereby solving the problem.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM