繁体   English   中英

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

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

我正在测试通过SSE接收数据

这是我的stream.php文件:

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

要接收数据,我使用:

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

当我使用document.getElementById("result") ,它会重复显示数据。 但是当我使用$("#result").html(e.data) ,它没有。 为什么呢

.innerHTML +=将添加到已经存在的HTML中,请注意+= ,而jQuery的html()方法每次都会覆盖HTML。

jQuery还有其他几种添加到现有标记中的方法,例如append()

使用+=e.data脚本+=e.data+=e.data新内容附加到现有标记中,但是.html()会覆盖现有值。

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

要么

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

.innerHTML+=+= .innerHTML+=内容追加到现有内容。 那相当于$("#result").html($("#result").html() + e.data);

暂无
暂无

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

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