使用ajax的post方式下载excel

项目需求,前端发起ajax请求,后端生成excel并下载,同时需要在header头中,带上token验证信息,参考了很多文章,最终实现如下:

PHP后端使用base64:

$filename = 'demo.xlsx';
$objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel2007');
ob_start();
$objWriter->save("php://output");
$xlsData = ob_get_contents();
ob_end_clean();
return Api::success(['filename' => $filename, 'file' => "data:application/vnd.ms-excel;base64," . base64_encode($xlsData)]);

JS前端:

$('.download').click(function(){

        var url = "http://xxxx.com/group/bi/export";
var params = {
from_date: '2017-09-01',
to_date: '2017-09-08',
group_id: 1
};
$.ajax({
type:'POST',
url: url,
data: params,
beforeSend: function(request) {
request.setRequestHeader("Authorization", "token信息,验证身份");
},
success: function(redata) { // 创建a标签,设置属性,并触发点击下载
var $a = $("<a>");
$a.attr("href", redata.data.file);
$a.attr("download", redata.data.filename);
$("body").append($a);
$a[0].click();
$a.remove();
}
});
});
上一篇:centos安装安全狗提示Need system command 'locate' to install safedog for linux的解决方法


下一篇:页面中多个script块之间的关系