ajax请求下载excel文件

改一个页面:js新打开一个页面,页面的地址为一个get请求接口,由于传递的字符串变多,要改为post请求。

没办法使用js打开新窗口这种了,考虑ajax请求。写个demo记录下

<script>
  function downloadFile(url, data) {
    $.ajax({
      url: url,
      type: "POST",
      cache: false,
      data: data,
      xhrFields: {
        responseType: "blob", // 设置响应类型为二进制流
      },
      beforeSend: function () {},
      success: function (response, status, xhr) {
        const blob = new Blob([response], {
          type: xhr.getResponseHeader("Content-Type"),
        });
        const link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        link.download = "test.xlsx";
        link.click();
      },
      complete: function (data) {},
      error: function (err) {},
    });
  }
</script>

 

posted @ 2024-03-07 17:19  carol2014  阅读(302)  评论(0编辑  收藏  举报