1.前端代码
前台页面,点击按钮,发送post请求。
<button id="export_data" type="button" class="btn btn-primary col-sm-5" style="margin-left: 10px" onclick="export_data()">导出excel</button>
function export_data(){
var csrf=$('input[name="csrfmiddlewaretoken"]').val();
const req = new XMLHttpRequest();
//请求连接
req.open('POST', '/product/export_data/', true);
req.responseType = 'blob';
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //设置请求头
//请求参数
req.send(
'product_name='+$("#product_name").val()+
'&&product_size='+$("#product_size").val()+
'&&product_brand='+brand_selected+
'&&product_model='+$("#product_model").val()+
'&&csrfmiddlewaretoken='+csrf); //输入参数
//返回结果
req.onload = function() {
debugger;
const data = req.response;
const blob = new Blob([data]);
const blobUrl = window.URL.createObjectURL(blob);
//模拟下载
download(blobUrl) ;
};
}
function download(blobUrl) {
debugger;
//创建a标签,用于保存excel
const a = document.createElement('a');
a.style.display = 'none';
//下载文件的名称拼接
var file_name_temp = "商品";
if($("#product_name").