$.ajax获取后台动态生成xlsx文件

需求:后台根据前端传递的参数动态生成xlsx文件模板,提供给前端下载。前端点击按钮下载文件。

下载函数:
function downloadFile(){
	const downLoadhref = `api/xxxxxxxxxxxxxxxx`
	const a = document.createElement("a");
	a.download = '文件模板';
	a.style.display = "none";
	a.href = downLoadhref;
	document.body.appendChild(a);
	a.click();
	document.body.removeChild(a);
}

问题:单纯的下载函数如果遇到正确生成的xlsx文件是能正常下载的,但是如果后台生成模板错误或者有报错信息的话直接下载带报错信息的.json文件。
解决:通过ajax下载,拿到response header头部信息,判断返回类型,如果是‘application/x-msexecl’则调取下载函数,否则提示错误,避免下载.json文件。

$.ajax({
  type:'get',
  url:'api/xxxxxxxxxxx', //请求api
  data:{}, //传递参数
  success: function(res,status,xhr){
    const xhrMessage = xhr.getResponseHeader("Content-Type").split(';')[0]
    if(xhrMessage==='application/x-msexecl'){
      // 调用downloadFile()方法
    }else{
      const {errCode,msg} = res //根据后台返回数据酌情修改
      if(errCode){
        console.error(msg)
      }
    }
  },
  error: function(res){
    console.log(res)
  }
})

注意点:$.ajax的scuccess带三个参数(返回值,请求状态,xhr对象),通过xhr.getResponseHeader(“Content-Type”) 获取信息做条件判断

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值