0


前端EventSource收不到流数据及EventSource的onmessage不执行问题

问题描述

在使用EventSource的onmessage接收后台数据时,发现不论怎么写,都没法在前端展示后台返回过来的数据,但是event.error和open是可以执行的,前段代码如下:

<!DOCTYPEhtml><html><head><metacharset="UTF-8"><title>EventSource Example</title></head><body><h1>get my page!</h1><divid="messages"></div><script>var source =newEventSource("/interface");
    source.onmessage=function(event){.//这里不执行// Update the content of the HTML page with the data received from the EventSource
        document.getElementById("messages").innerHTML += event.data;};
    source.onerror=function(event){//这却能执行
        console.log("EventSource error:", event);};
    source.onopen=function(event){//这也能执行  
        console.log("EventSource connection opened");};</script></body></html>

解决方法

EventSource在前端是有自己的一套解析格式的,即:

event: message\n
data: {BackendValue}\n\n

其中,BackendValue是你要返回给前端的内容。
所以我们后端返回数据时,比如你要返回一个字符串,那就把字符串的头部拼接上

event: message\ndata: 

, 并把字符串的尾部拼接上

\n\n

,即在你的数据尾部增加两个换行回车。
JSP格式的表示如下:

out.write("event: message\n");
out.write("data:"+ value +"\n\n");

应该看得很清楚了,如果还不理解,看一下我推荐的几篇文章,就懂了。
参考这篇文章:EventSource onmessage() is not working
参考这篇论坛讨论:EventSource的onmessage不执行

标签: javascript 前端 java

本文转载自: https://blog.csdn.net/zoubaihan/article/details/130700056
版权归原作者 zoubaihan 所有, 如有侵权,请联系我们删除。

“前端EventSource收不到流数据及EventSource的onmessage不执行问题”的评论:

还没有评论