簡體   English   中英

使用XMLHTTPRequest從JavaScript工作者進行輪詢

[英]Polling from a JavaScript worker using XMLHTTPRequest

我正在嘗試創建一個同時執行以下操作的工作程序:

  1. 將XMLHTTPRequest發送到服務器以執行任務(這可能需要很長時間)

  2. 每隔X秒發送一次XML HTTP請求消息,以獲取有關該進程的更新,直到進程(1)完成。

我到目前為止所擁有的是下面。 但是它不會輪詢。 第一部分成功執行。 第二位僅運行一次。 有人知道我在做什么錯嗎?

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

查看方法,您可以看到第三個參數是異步的

 open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);

通過將其設置為false,您將告訴它同步運行,這意味着在返回調用之前不會發生任何其他事情。 這將導致您的輪詢代碼在返回第一個調用后運行。 將其設置為異步運行,並使用onreadystatechange獲取完成時間!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM