从Web Worker执行AJAX请求是否可行?
我似乎无法在我的webworker中使用jQuery,我知道必须有一种方法来使用XMLHttpRequest
,但是当我读到这个答案时,似乎这可能不是一个好的选择。
当然你可以在你的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');
您可能希望阅读这个答案,了解如果您通过Webworkers有太多的 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更清晰)。