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.
Ajax is not inherently secure or insecure. It does however open up 'opportunities' for insecure code.
Ajax should be used anywhere in a web application where small amounts of information could be saved or retrieved from the server without posting back the entire pages. A good example of this is data validation on save actions.
AJAX can change data without reloading the web page. In other words, it implements partial server requests. The main difference among the three is that JavaScript is client-side, i.e., in the browser scripting language, whereas jQuery is a library (or framework) built with JavaScript.
Of course you can use AJAX inside of your webworker, you just have to remember that an AJAX call is asynchronous and you will have to use callbacks.
This is the ajax
function I use inside of my webworker to hit the server and do AJAX requests:
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 might want to read this answer about some of the pitfalls that might happen if you have too many AJAX requests going through webworkers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With