簡體   English   中英

在 XMLHttpRequest 完成后運行 then 方法

[英]Running then method after XMLHttpRequest done

我有一個像異步方法一樣的方法。 在請求發送到調用此請求的函數后,我想運行類似 then 方法的內容,但隨后沒有用於 XMLHttpRequest 的 then 方法。 下面代碼中的調用函數沒有 then 方法

      let result = dataService.exportfile('get', '/api/overtimeedari/exporttoexcle/', model).
                then(() => {
                        self.loading(false);//غیرفعال کردن حالت لود  شدن گرید
                        buttonListSearch.Excel.loading(false); //غیرفعال کردن حالت لود شدن دکمه اکسل
                    });

調用的函數

        function exportfile(mehtodtype, url, model) {
            debugger;
            var qs = "?";
            model.map((item) => {
                qs = `${qs}${item.name}=${item.value}&`;
            });

            var request = new XMLHttpRequest();
            request.open(mehtodtype, url + qs, true);
            request.setRequestHeader('Authorization', "Bearer " + window.localStorage.getItem('token'));
            request.responseType = 'blob';
            request.onload = function (e) {
                if (this.status === 200) {
                    var blob = this.response;
                    if (window.navigator.msSaveOrOpenBlob) {
                        window.navigator.msSaveBlob(blob, fileName);
                    }
                    else {
                        var downloadLink = window.document.createElement('a');
                        var contentTypeHeader = request.getResponseHeader("Content-Type");
                        downloadLink.href = window.URL.createObjectURL(new Blob([blob], { type: contentTypeHeader }));
                        downloadLink.download = "Export.xls";
                        document.body.appendChild(downloadLink);
                        downloadLink.click();
                        document.body.removeChild(downloadLink);
                    }
                }
            };
            request.send();
            return request;
        }

鑒於不根據評論更改exportfile功能的約束

情況是我沒有更改exportfile功能的能力,因為它對其他功能有副作用

處理這個問題的最佳方法如下

let req = dataService.exportfile('get', '/api/overtimeedari/exporttoexcle/', model);
req.addEventListener('loadend', () => {
  // do what's needed here
});

由於exportfile返回 XMLHttpRequest 對象,因此您可以偵聽loadend事件並在那里執行任何操作

注意,無論成功還是失敗都會觸發loadend事件

如果您願意,您也可以使用load事件執行上述操作 - 但是,我不確定什么順序

x.onload=() => {};
x.addEventListener('load', () => {});

被解雇了……還要注意,不要

req.onload=() => {};

因為這會覆蓋函數內的 onload 回調

暫無
暫無

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

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