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

Is it feasible to do an AJAX request from a Web Worker?

本文关键字:是否 请求 AJAX Web Worker 执行      更新时间:2023-09-26

我似乎无法在我的网络工作者中使用jQuery,我知道一定有一种方法可以用XMLHttpRequest做到这一点,但是当我阅读这个答案时,这似乎不是一个好的选择。

当然,您可以在Webworker中使用AJAX,您只需要记住AJAX调用是异步的,并且必须使用回调。

这是我在 Web worker 内部用来攻击服务器并执行 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');

您可能希望阅读此答案,了解通过 Web Worker 的 AJAX 请求过多时可能发生的一些陷阱。

如果尝试在使用 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

只需使用 Fetch API 中的 JS 函数 fetch()。您还可以设置许多选项,例如 CORS 绕过等(因此您可以实现与 importScripts 相同的行为,但使用 Promise 的方式更简洁)。

代码如下所示:

var _params = { "param1": value};
fetch("http://localhost/Service/example.asmx/Webmethod", {
    method: "POST",
    headers: {
        "Content-Type": "application/json; charset=utf-8"
    },
    body: JSON.stringify(_params )
}).then(function (response) {
    return response.json();
}).then(function (result) {
    console.log(result);
});

Web服务的web.config看起来像这样:

<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
                <add name="Access-Control-Allow-Headers" value="Content-Type" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>