how to send xmlhttprequest continuously in webworker?

偶尔善良 提交于 2019-12-17 17:22:45

问题


I am new to webworker but I managed to send xmlhttprequest to my rest api and I got json back. But I want send this request again and again (in a loop), until the page is active. I actually want to show values in real time. I want to make a simple web application in which when data is inserted in database my webworker should show that data without refreshing the page. Is there any better way to do so. Kindly help me in it. sorry for bad English.


回答1:


You can use EventSource to get stream from server until .close() is called at Worker, or message is passed to Worker signalling Worker to call .close().

const es = new EventSource("/path/to/server");
es.addEventListener("open", function(event) {
  console.log("event source open")
});
es.addEventListener("message", function(event) {
  // do stuff with `event.data`
  console.log(event.data);
});
es.addEventListener("error", function(event) {
  console.log("event source error", event)
});

button.addEventListener("click", function() {
  es.close();
});


来源:https://stackoverflow.com/questions/42512572/how-to-send-xmlhttprequest-continuously-in-webworker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!