qwe*_*ynl 21 javascript ajax jquery web-worker
我似乎无法在我的webworker中使用jQuery,我知道必须有一种方法可以实现它XMLHttpRequest,但是当我读到这个答案时,似乎这可能不是一个好的选择.
qwe*_*ynl 28
当然你可以在你的webworker中使用AJAX,你只需要记住一个AJAX调用是异步的,你将不得不使用回调.
这是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;
};
Run Code Online (Sandbox Code Playgroud)
然后你的工作人员可以做到:
ajax(url, {'send': true, 'lemons': 'sour'}, function(data) {
//do something with the data like:
self.postMessage(data);
}, 'POST');
Run Code Online (Sandbox Code Playgroud)
您可能想要阅读这个答案,了解如果您通过Webworkers 有太多的 AJAX请求可能会发生的一些陷阱.
| 归档时间: |
|
| 查看次数: |
16380 次 |
| 最近记录: |