//创建xhr对象
var xhr = new XMLHttpRequest();
//设置xhr请求的超时时间
xhr.timeout = 3000;
//设置响应返回的数据格式
xhr.responseType = "arraybuffer";
//创建一个 post 请求,采用异步
xhr.open('GET', '<url>', true);
//注册相关事件回调处理函数
xhr.onload = function(e) {
if(this.status == 200||this.status == 304) {
let res = 'response' in xhr ? xhr.response : xhr.responseText
// 设置文件类型,这里以excel为例,并创建一个blob
let blob = new Blob([res], {type: "application/vnd.ms-excel;charset=utf-8"});
// 创建一个临时URL
let url = window.URL.createObjectURL(blob);
// 添加
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
// 设置下载名称
a.download = 'example.xls';
a.click();
window.URL.revokeObjectURL(url);
}
};
// 超时回调
xhr.ontimeout = function(e) {
};
// 错误回调
xhr.onerror = function(e) {
};
// 上传进度回调
xhr.upload.onprogress = function(e) {
};
// 设置请求头
xhr.setRequestHeader(header, value);
xhr.setRequestHeader('Authorization', token);
//发送数据
xhr.send();
网友评论