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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20663353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:59:26  来源:igfitidea点击:

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

javascriptjqueryajaxweb-worker

提问by qwertynl

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.

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

回答by qwertynl

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

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

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

这是ajax我在 webworker 内部使用的函数来访问服务器并执行 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;
};

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');

You mightwant to read this answerabout some of the pitfalls that might happen if you have too manyAJAX requests going through webworkers.

如果您有太多的AJAX 请求通过 webworkers,您可能想阅读有关可能发生的一些陷阱的答案

回答by rbrundritt

If trying to call a service on another domain that uses JSONP, you can use the importScripts function. For example:

如果尝试调用另一个使用 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();

Found this great tip here: http://cggallant.blogspot.com/2010/10/jsonp-overview-and-jsonp-in-html-5-web.html

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

回答by lukyer

Just use JS function fetch()from Fetch API. You can also set up a lot of options like CORSbypassing and so on (so you can achieve the same behavior like with importScriptsbut in much cleaner way using Promises).

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

the code looks like this:

代码如下所示:

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

and the web.config of the webservice looks like this:

并且 webservice 的 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>