<code>javascript: var e = new EventSource('test.php'); e.onopen = function(){ console.log('你创建了一个服务器长连接!'); }; e.onmessage = function(event){ var e = event || window.event; console.log('接受到来自服务器的消息: ' + event.data); } e.onerror = function(event){ console.log('链接发生错误,当前链接状态: ' + event.readyState); } PHP: header('content-type:text/event-stream'); header('cache-control:no-cache'); while (true) { echo 'hello world'; ob_flush(); flush(); sleep(1); } </code>
在瀏覽器中開啟請求的 event_source.php 查看,如下圖:
不理解 這裡的 EventStream 是怎樣的回應類型....,為什麼 onmessage 方法一直接受不到任何資料(因為途中的EventStream 欄下 沒有接收到任何資訊...) , 這是怎麼回事? ?我後台輸出的是字串,是否需要對該字串做型別轉換? ?
<code>javascript: var e = new EventSource('test.php'); e.onopen = function(){ console.log('你创建了一个服务器长连接!'); }; e.onmessage = function(event){ var e = event || window.event; console.log('接受到来自服务器的消息: ' + event.data); } e.onerror = function(event){ console.log('链接发生错误,当前链接状态: ' + event.readyState); } PHP: header('content-type:text/event-stream'); header('cache-control:no-cache'); while (true) { echo 'hello world'; ob_flush(); flush(); sleep(1); } </code>
在瀏覽器中開啟請求的 event_source.php 查看,如下圖:
不理解 這裡的 EventStream 是怎樣的回應類型....,為什麼 onmessage 方法一直接受不到任何資料(因為途中的EventStream 欄下 沒有接收到任何資訊...) , 這是怎麼回事? ?我後台輸出的是字串,是否需要對該字串做型別轉換? ?
因為你 echo 裡面輸出的文字內容格式不對。
每一次 echo 的內容,都必須是如下格式
<code>field: value </code>
field 可以是 data, event, id, retry 這四個中的任一個
value 為資料有效載荷
你這裡的例子,應該改為
<code>echo "data: hello world\n\n"; </code>
參考資料:
https://www.mxgw.info/t/serve...
http://javascript.ruanyifeng....
https://developer.mozilla.org...
php裡面沒有加php標識符?
瀏覽器裡面訪問php文件, js一定不能收到訊息, 要建個html,瀏覽器裡面訪問html。