使用XMLHTTPRequest从JavaScript工作程序进行轮询
我正在尝试创建一个同时执行以下操作的worker:使用XMLHTTPRequest从JavaScript工作程序进行轮询,javascript,asynchronous,xmlhttprequest,polling,worker,Javascript,Asynchronous,Xmlhttprequest,Polling,Worker,我正在尝试创建一个同时执行以下操作的worker: 向服务器发送XMLHTTPRequest以执行任务(可能会 (需要很长时间) 每X秒发送一条XML HTTP请求消息,以获取进程的更新,直到进程(1)完成 到目前为止,我所了解的情况如下。但它没有投票权。第一部分已成功执行。第二位只运行一次。有人知道我做错了什么吗 onmessage = function (e) { e.data.params.task = "runTask"; // The server understands this.
onmessage = function (e) {
e.data.params.task = "runTask"; // The server understands this. This performs(1)
// Sends an asynchronous request to perform (1)
var xhr = new XMLHttpRequest();
xhr.open('POST', e.data.url, false);
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(JSON.stringify(e.data.params));
// initialise polling
var interval = 500;
// Poll until (1) is complete
(function poll(){
if (xhr.readyState != 4){ // while (1) is yet to be completed..
e.data.params.task = "getProgress";
// Send another request to the server to get an update on the first process
var pollxhr = new XMLHttpRequest();
pollxhr.open('POST', e.data.url, true);
pollxhr.setRequestHeader("Content-type", "application/json");
pollxhr.timeout = interval;
pollxhr.ontimeout = poll; // This should cause the process to poll
pollxhr.onreadystatechange = function(){
e.data.progress = pollxhr.responseText;
postMessage(e.data);
};
pollxhr.send(JSON.stringify(e.data.params));
}else{
e.data = xhr.responseText;
postMessage(e.data);
}
})();
};
问题在于第一个电话
xhr.open('POST', e.data.url, false);
^^^^^
查看该方法,您可以看到第三个参数是async
open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);
通过将其设置为false,您告诉它同步运行,这意味着在返回调用之前不会发生任何其他事情。这将导致在返回第一个调用后运行轮询代码。将其设置为异步运行,并在完成时使用onreadystatechange获取 在我将参数更改为“true”表示异步后,它的行为仍然类似。是否因为请求在超时之前完成,所以轮询没有被递归调用?我已经查看了超时,但不清楚即使在超时时间过去之前响应成功,请求是否也会耗尽超时值。您应该在readystate达到4时调用Ajax调用。