Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

php - I cannot see HTML5 EventSource event with onmessage method in Chrome

I tried to use the EventSource object with a little example

On the client side, I have this page with the following script :

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Welcome!</title>
    </head>
    <body>
        <div id="result"></div>
        <script type="text/javascript">
        var sse = new EventSource('event-source.php');
        
        sse.onmessage = function(event) {
            console.log(event.data);
            document.getElementById("result").innerHTML+=event.data + "<br>";
        }

        sse.onerror = function(event) {
        console.log(event);
        }
        
        </script>
    </body>
</html>

script calls event-source.php on server. Here is event-source.php :

<?php
header('Content-type: text/event-stream');
echo 'data: '.time().PHP_EOL;

When I try this configuration on Firefox, the method "onMessage" is well called, but not with Chrome. When I put the "onError" method, it seems that it is called but I cannot see the error cause.

What should I do?

question from:https://stackoverflow.com/questions/13209386/i-cannot-see-html5-eventsource-event-with-onmessage-method-in-chrome

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CLIENT

<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("/html/demo_sse.php");
source.onopen = function() {
document.getElementById("myH1").innerHTML = "Getting server updates";
};
source.onmessage = function(event) {
document.getElementById("myDIV").innerHTML += event.data + "<br>";
};        
} else {
document.getElementById("myDIV").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>

SERVER

<?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');

    $time = date('r');
    echo "data: The server time is: {$time}

";
    flush();
    ?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...