我尝试使用数据库中的某些数据实时更新HTML5表。这是我的代码:
HTML页面:
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("[some address]/api/sse");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("placeholder").innerHTML=table;
};
}
else {
[erro message]
}
</script>
我的Java Restful服务:
@Path("/sse")
public class SSEResource {
@Context
private UriInfo context;
public SSEResource() {
}
@GET
@Produces(SseFeature.SERVER_SENT_EVENTS)
public String getServerSentEvents() throws Exception {
SomeObject o = new SomeObject();
final String myString = o.someQuery().getEntity().toString();
return "data: " + myString + "\n\n";
}
}
这个someQuery()
方法从数据库查询并返回我想要放在我的表上的内容。 Everythings看起来很棒。但我想知道它是对还是错,因为如果我对someQuery()
方法进行了一些登录,我会看到每3秒执行一次查询。这可能会导致重负,对吧?这是正常的还是我的代码错了?