简体   繁体   中英

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

I'm testing to receive data with SSE

This is my stream.php file:

<?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. But when I use $("#result").html(e.data) , it doesn't. Why ?

.innerHTML += adds to the already exsisting HTML, note the += , while jQuery's html() method overwrites the HTML every time.

jQuery has several other methods that adds to the existing markup, like append() .

Using the vanila script +=e.data you are appending the new content to the existing markup, but .html() overrides the existing values.

$("#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. That would be equivalent to $("#result").html($("#result").html() + e.data);

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