来自网络工作者的中止ajax呼叫

时间:2018-07-16 15:31:09

标签: javascript ajax xmlhttprequest web-worker

我今天阅读了一些有关Web Workers的文章,并且尝试了一些有关Ajax请求的内容。实际上,我希望能够存储Web Worker发送的每个ajax请求,以便在单击元素时中止它们。 但是,无法克隆XHR对象,因此无法通过postMessage()worker方法发送该对象。

我尝试过这种方式:

    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
    let DONE = 4; // readyState 4 means the request is done.
    let OK = 200; // status 200 is a successful return.
    if (xhr.readyState === DONE) {
        if (xhr.status === OK) {
            handlePoints(JSON.parse(xhr.responseText));
        }
    }

    xhr.open('GET', '/api/widgets/burndownchart?widgetId='+ widgetId);
    xhr.send(null);
    self.postMessage([constants.EVENT_AJAX_CALL, xhr]);

但是我当然有这个错误:

  

未捕获的DOMException:无法在'DedicatedWorkerGlobalScope'上执行'postMessage':无法克隆XMLHttpRequest对象。

您对如何执行此操作有想法吗? PS:对不起,我的语言错误。

1 个答案:

答案 0 :(得分:0)

您需要将对象保留在Web Worker中,并向Web Worker发送一条消息,要求其按需中止请求。

相关问题