【问题标题】:Is it feasible to do an AJAX request from a Web Worker?从 Web Worker 发出 AJAX 请求是否可行?
【发布时间】:2014-01-06 22:31:48
【问题描述】:

我似乎无法在我的 webworker 中使用 jQuery,我知道XMLHttpRequest 一定有办法做到这一点,但是当我阅读this answer 时,这似乎不是一个好的选择。

【问题讨论】:

  • 我认为 ajax 现在在所有常见的 webworker 实现中。添加它需要一段时间,完全使用 ajax2,但现在已经相当稳定了。
  • ajax2?需要解释一下吗?
  • XMLHttpRequest 级别 2:caniuse.com/xhr2
  • 你能举个例子吗?
  • 不,jQuery 在 web worker 中不起作用。你可以使用普通的 JS。你也许可以让 Zepto 或一些 node.js DOM 工作,但这比简单地使用 iframe 做的工作要多得多,它可以运行 jQuery、jsonp 调用等......

标签: javascript jquery ajax web-worker


【解决方案1】:

当然你可以在你的 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');

可能想阅读this answer,了解如果您有太多通过网络工作者的 AJAX 请求可能发生的一些陷阱。

【讨论】:

  • 要发送 JSON 对象,您需要按照 req.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); data_string = JSON.stringify(data);
【解决方案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

【讨论】:

    【解决方案3】:

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

    代码如下所示:

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

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-03
      • 2011-11-20
      • 1970-01-01
      • 2012-08-26
      • 2015-05-27
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多