简体   繁体   English

document.getElementById与jQuery $ html()一起接收服务器发送的事件数据

[英]document.getElementById vs jQuery $html() to receive Server-sent Event Data

I'm testing to receive data with SSE 我正在测试通过SSE接收数据

This is my stream.php file: 这是我的stream.php文件:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: test\n\n";
flush();
?>

To receive data I use: 要接收数据,我使用:

var source=new EventSource("stream.php");
    source.onmessage=function(e)
    {
      //document.getElementById("result").innerHTML+=e.data + "<br/>";
        $("#result").html(e.data);
    };

When I use document.getElementById("result") , it show the data repeatedly. 当我使用document.getElementById("result") ,它会重复显示数据。 But when I use $("#result").html(e.data) , it doesn't. 但是当我使用$("#result").html(e.data) ,它没有。 Why ? 为什么呢

.innerHTML += adds to the already exsisting HTML, note the += , while jQuery's html() method overwrites the HTML every time. .innerHTML +=将添加到已经存在的HTML中,请注意+= ,而jQuery的html()方法每次都会覆盖HTML。

jQuery has several other methods that adds to the existing markup, like append() . jQuery还有其他几种添加到现有标记中的方法,例如append()

Using the vanila script +=e.data you are appending the new content to the existing markup, but .html() overrides the existing values. 使用+=e.data脚本+=e.data+=e.data新内容附加到现有标记中,但是.html()会覆盖现有值。

$("#result").append(e.data + '<br/>')

or 要么

$("#result").html(function(_, html){
    return html += e.data + '<br/>';
})

The += in .innerHTML+= is appending the content to the existing content. .innerHTML+=+= .innerHTML+=内容追加到现有内容。 That would be equivalent to $("#result").html($("#result").html() + e.data); 那相当于$("#result").html($("#result").html() + e.data);

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

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