Home > Article > Backend Development > Some problems encountered when learning EventSource objects in javascript? ?
<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>
Open the requested event_source.php in the browser to view, as shown below:
I don’t understand what kind of response type the EventStream here is..., why the onmessage method never receives any data (because no information is received under the EventStream column on the way...), what is going on? ? What I output in the background is a string. Do I need to perform type conversion on the string? ?
<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>
Open the requested event_source.php in the browser to view, as shown below:
I don’t understand what kind of response type the EventStream here is..., why the onmessage method never receives any data (because no information is received under the EventStream column on the way...), what is going on? ? What I output in the background is a string. Do I need to perform type conversion on the string? ?
Because the format of the text output in your echo is wrong.
The content of each echo must be in the following format
<code>field: value </code>
field can be any one of data, event, id, retry
value is the data payload
Your example here should be changed to
<code>echo "data: hello world\n\n"; </code>
Reference:
https://www.mxgw.info/t/serve...
http://javascript.ruanyifeng....
https://developer.mozilla.org...
There is no php identifier in php?
When accessing the php file in the browser, js will definitely not receive the message. To create an html, access the html in the browser.