2017-06-15 106 views
0

這是我的代碼:爲什麼我的websse返回null?

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> 
+3

歡迎來到SO,你的問題是什麼重刑,你到目前爲止嘗試過什麼?請儘量詳細說明。 –

+0

我想PHP代碼返回時間,但它不起作用。 PHP代碼可以回顯時間成功,但頁面無法收到時間 –

回答

2

您需要添加2換行字符之後的任何數據輸出你的websse.php腳本,所以:

<?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 
+0

它的工作原理。但我不明白。這是規定的格式嗎? –

+1

是的:https://www.html5rocks.com/en/tutorials/eventsource/basics/ - 向下滾動到** Event Stream格式** – CD001

+0

感謝您的幫助* 3! └(^ O ^)┘ –