简体   繁体   English

html5 - 服务器端事件:替换行而不是追加

[英]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.我的目标是使用 HTML5 SSE(服务器端事件)将数据更新从服务器发送到客户端。 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.我在 php 文件中使用 [\\n\\n] 来停止流。

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].我希望替换在同一个地方,因此被保存在 div [result] 内。

I have tried to remove the br-tag at line 17 of the html-file, but it did not remove the "newline".我试图删除 html 文件第 17 行的 br 标签,但它没有删除“换行符”。

My html5 file, with js included:我的 html5 文件,包括 js:

  <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 文件:

<?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:在您的source.onmessage回调中,只需将行更改为:

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.现在,使用=它会覆盖旧结果,从而解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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