jquery post 下载(Excel)文档加载后打开是乱码

凌晨4点5杀老大爷 2019-03-19 06:27:48
需要post 将Excel文件流下载到本地 然后打开 但是显示有乱码

$.ajax({
type: "POST",
url: .......,
data: {
.......
},
responseType: 'blob',
success: function (response, status, request) {
var disp = request.getResponseHeader('Content-Disposition');
if (disp && disp.search('attachment') != -1) { //判断是否为文件
//var form = $('<form method="POST" action="' + url + '">');
//$.each(params, function (k, v) {
// form.append($('<input type="hidden" name="' + k +
// '" value="' + v + '">'));
//});
//$('body').append(form);
console.log(111);
var fileName = '......xls';
var content = response;
var blob = new Blob([content]);
const elink = document.createElement('a')
elink.download = fileName;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
}
}
});

请教如何解决乱码问题。
...全文
705 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复 1
引用 5 楼 BinaryLizm 的回复:
$.ajax 的 responseType 不是这样设置的

$.ajax({
    type: "POST",
    responseType: 'blob' // 无效
})
是这样设置的

$.ajax({
    type: "POST",
    xhrFields:{
        responseType: 'blob'
    }
})
但是$.ajax 不支持接受 responseType 为blob 时的 responseText 源码如下:

// Support: IE<10
// Accessing binary-data responseText throws an exception
// (#11426)
if ( typeof xhr.responseText === "string" ) {  // 设置了 responseType 为 blob 或者 arraybuffer 时,这一句报错
    responses.text = xhr.responseText;
}
所以使用 $.ajax post 来接受后端返回的流数据无解,不是硬性要求使用 $.ajax 做的话,网上有很多其他解决方法,原生或者axios等。
不喜jquery
asu.lzm 2020-02-27
  • 打赏
  • 举报
回复
$.ajax 的 responseType 不是这样设置的

$.ajax({
    type: "POST",
    responseType: 'blob' // 无效
})
是这样设置的

$.ajax({
    type: "POST",
    xhrFields:{
        responseType: 'blob'
    }
})
但是$.ajax 不支持接受 responseType 为blob 时的 responseText 源码如下:

// Support: IE<10
// Accessing binary-data responseText throws an exception
// (#11426)
if ( typeof xhr.responseText === "string" ) {  // 设置了 responseType 为 blob 或者 arraybuffer 时,这一句报错
    responses.text = xhr.responseText;
}
所以使用 $.ajax post 来接受后端返回的流数据无解,不是硬性要求使用 $.ajax 做的话,网上有很多其他解决方法,原生或者axios等。
  • 打赏
  • 举报
回复
引用 3 楼 qq_783939100 的回复:
是不是编码问题
没有多余时间研究 变通处理了 ,理论上应该是可行的
qq_783939100 2019-03-22
  • 打赏
  • 举报
回复
是不是编码问题
  • 打赏
  • 举报
回复
自己解决了 不用post下载,用post生成到服务器 返回下载链接 客户端下载
麦草CMS 2019-03-20
  • 打赏
  • 举报
回复
我不清楚。关键是Excel表格不是普通的文本文件。js怎么可能就你的一句js代码就能渲染在网页中。得有一个复杂的算法把它转换一下吧。你搜一下,应该有这样的js库。

87,910

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧