检查下面的代码,这里我已经为每个事件类型添加了三条警报消息,但在此代码中source.onopen()[alert:readyState:1]和source.onerror()[alert:readyState:0]正常工作但在onmessage()的情况它没有被执行
if(typeof(EventSource) !== "undefined") {
var source = new EventSource('clinic/get');
source.onopen = function(){
alert('connection is opened.'+source.readyState);
};
source.onerror = function(){
alert('error: '+source.readyState);
};
source.onmessage = function(datalist){
alert("message: "+datalist.data);
};
} else {
document.getElementById("clinic-dtls").innerHTML = "Sorry, your browser does not support server-sent events...";
}`
Run Code Online (Sandbox Code Playgroud)
检查服务器端的以下代码
Random random = new Random();
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
System.out.println("clinic/get got hit");
try {
Writer out = response.getWriter();
out.write("data: welcome data"+random);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
我正在使用STS(Spring工具套装),我想知道,当我在EventSource(源)对象上使用ctrl + space时,在选项中它只显示onopen()和onerror(),其中是onmessage().
如果我得到任何回复,我将非常感激. - 谢谢
Pap*_*ppa 17
我认为正确的格式是:
out.write("event: message\n");
out.write("data:" + value + "\n\n");
Run Code Online (Sandbox Code Playgroud)
该onmessage处理器假设事件名称message。如果要使用其他事件名称,可以使用 订阅它们addEventListener。
Ram*_*Ram 11
解决了!!!
代码没有问题,实际问题是当我向客户端写回复时,我的响应消息应该如下所示.
PrintWriter out = response.write("data: message"+value+"\n\n");
out.flush(); //don't forget to flush
Run Code Online (Sandbox Code Playgroud)
在我的代码中,我错过了响应对象中的最后一部分"\n \n",因此source.onmessage(datalist)在javascript中没有被击中.
疯狂的编码..
| 归档时间: |
|
| 查看次数: |
6245 次 |
| 最近记录: |