【发布时间】:2021-10-02 02:09:16
【问题描述】:
我有一个类似于异步方法的方法。在请求发送到调用这个请求的函数之后,我想运行类似 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;
}
【问题讨论】:
-
XHMHttpRequest 没有
.then属性——你可能在想fetch吗?或其他返回承诺的东西?承诺是具有.then方法的东西 - 如果您绝对必须使用XMLHttpRequest,您当然可以将function exportfile中的代码包装在Promise 中 -
@Bravo 我需要在 XMLHttpRequest 完成后运行回调函数之类的东西。
-
当然,然后这样做 - 向
exportfile提供一个回调函数并在需要时调用它 - 这也有效 -
@Bravo 情况是我没有这种能力来改变`exportfile`功能,因为它对其他功能有副作用
标签: javascript c# xmlhttprequest