从Web Worker执行AJAX请求是否可行?

时间:2013-12-18 16:27:49

标签: javascript jquery ajax web-worker

我似乎无法在我的webworker中使用jQuery,我知道必须有一种方法可以使用XMLHttpRequest,但是当我阅读{{{}时,似乎这可能不是一个好的选择。 3}}

3 个答案:

答案 0 :(得分:27)

当然你可以在webworker中使用AJAX,你只需记住 AJAX调用是异步的,你将不得不使用回调。

这是我在webworker中使用的ajax函数来命中服务器并执行AJAX请求:

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

然后在你的工作人员中你可以做到:

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

答案 1 :(得分:2)

如果尝试在另一个使用JSONP的域上调用服务,则可以使用importScripts函数。例如:

// Helper function to make the server requests 
function MakeServerRequest() 
{ 
importScripts("http://SomeServer.com?jsonp=HandleRequest"); 
} 

// Callback function for the JSONP result 
function HandleRequest(objJSON) 
{ 
// Up to you what you do with the data received. In this case I pass 
// it back to the UI layer so that an alert can be displayed to prove 
// to me that the JSONP request worked. 
postMessage("Data returned from the server...FirstName: " + objJSON.FirstName + " LastName: " + objJSON.LastName); 
} 

// Trigger the server request for the JSONP data 
MakeServerRequest();

在这里找到了这个很棒的提示:http://cggallant.blogspot.com/2010/10/jsonp-overview-and-jsonp-in-html-5-web.html

答案 2 :(得分:2)

只需使用 Fetch API 中的JS函数 fetch()即可。您还可以设置很多选项,例如 CORS 绕过等等(这样您就可以实现与 importScripts 相同的行为,但使用 Promises可以更清晰地实现)。

相关问题