如何在webworker中连续发送xmlhttprequest? [英] how to send xmlhttprequest continuously in webworker?

查看:1185
本文介绍了如何在webworker中连续发送xmlhttprequest?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是webworker的新手,但我设法将xmlhttprequest发送到我的rest api,然后我让json回来了。但我希望一次又一次地(循环)发送此请求,直到页面处于活动状态。
我实际上想要实时显示价值。我想制作一个简单的Web应用程序,当数据插入数据库时​​,我的webworker应该在不刷新页面的情况下显示数据。
有没有更好的方法。请帮助我。
对不起英语抱歉。

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.

推荐答案

您可以使用 EventSource 从服务器获取流直到 .close() Worker 中调用,或者消息传递给 Worker 发信号工人致电 .close()

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();
});

这篇关于如何在webworker中连续发送xmlhttprequest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆