Problem Description
When using EventSource's onmessage to receive background data, I found that no matter how I write it, the data returned from the background cannot be displayed on the front end, but event.error and open can be executed. The front code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EventSource Example</title>
</head>
<body>
<h1>get my page!</h1>
<div id="messages"></div>
<script>
var source = new EventSource("/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>
Solution
EventSource has its own set of parsing formats on the front end, namely:
event: message\n
data: {BackendValue}\n\n
Among them, BackendValue is the content you want to return to the front end.
So when our backend returns data, for example, if you want to return a string, then splice the head of the string event: message\ndata:
and the tail of the string \n\n
, that is, add two line feeds and carriage returns at the end of your data.
The representation of JSP format is as follows:
out.write("event: message\n");
out.write("data:" + value + "\n\n");
You should see it clearly. If you still don’t understand it, just read some of the articles I recommend and you’ll understand.
Refer to this article: EventSource onmessage() is not working
Refer to this forum discussion: EventSource's onmessage is not executed