为什么我的websse返回null?

时间:2017-06-15 09:02:27

标签: php html5

这是我的代码:

PHP:

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

$time = date('Y-m-d H:i:s');

echo  "data: now time is ".$time;

flush();

HTML:

 <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>websse</title>
    </head>
    <body>
        <p id='pp'></p>

        <script>

            if(typeof(EventSource)!== 'undefined'){
                es = new EventSource('websse.php');
                es.onmessage=function(event)
                {
                    document.getElementById("pp").innerHTML+=event.data + "<br>";
                    console.log(event.data);
                };

            }else{
                p.innerHTML = "--------";
            }
        </script>
    </body>
    </html>

1 个答案:

答案 0 :(得分:2)

You need to add 2 newline characters after any data is output in your websse.php script, so:

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

$time = date('Y-m-d H:i:s');
echo "data: now time is " . $time . "\n\n"; // <-- here