簡體   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