它是做从Web工作者AJAX请求是否可行? [英] Is it feasible to do an AJAX request from a Web Worker?

查看:92
本文介绍了它是做从Web工作者AJAX请求是否可行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎不能够使用jQuery在我webworker,我知道必须有一个方式与 XMLHtt prequest 做到这一点,但它似乎这样可能不是一个很好的选择,当我读到这个答案

I do not seem to be able to use jQuery in my webworker, I know there must be a way to do it with XMLHttpRequest, but it seems like that might not be a good option when I read this answer.

推荐答案

当然:您可以使用AJAX你webworker里面,你就必须为记住是一个AJAX电话是异步的,你将不得不使用回调。

Of course you can use AJAX inside of your webworker, you just have to remember that an AJAX call is asynchronous and you will have to use callbacks.

这是 AJAX 功能我用我的webworker内打服务器,并执行AJAX请求:

This is the ajax function I use inside of my webworker to hit the server and do AJAX requests:

var ajax = function(url, data, callback, type) {
  var data_array, data_string, idx, req, value;
  if (data == null) {
    data = {};
  }
  if (callback == null) {
    callback = function() {};
  }
  if (type == null) {
    //default to a GET request
    type = 'GET';
  }
  data_array = [];
  for (idx in data) {
    value = data[idx];
    data_array.push("" + idx + "=" + value);
  }
  data_string = data_array.join("&");
  req = new XMLHttpRequest();
  req.open(type, url, false);
  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  req.onreadystatechange = function() {
    if (req.readyState === 4 && req.status === 200) {
      return callback(req.responseText);
    }
  };
  req.send(data_string);
  return req;
};

然后你的工人在里面可以做的:

Then inside your worker you can do:

ajax(url, {'send': true, 'lemons': 'sour'}, function(data) {
   //do something with the data like:
   self.postMessage(data);
}, 'POST');

您的也许的想读这个答案一些,如果可能发生的陷阱你的太多 AJAX请求经历webworkers。

You might want to read this answer about some of the pitfalls that might happen if you have too many AJAX requests going through webworkers.

这篇关于它是做从Web工作者AJAX请求是否可行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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