ajax导出表格或附件
//导出
$('#dr_export').click(function () {
var batch = $('#dr_export_input').val();
if(!batch){
Layer.alert('请输入批次');
return false;
}
var url = '/VMPEGxrtdk.php/scode/exportOrderExcel';
$.ajax({
url: url, // 替换为你的 PHP 脚本路径
method: 'GET',
data: {
batch:batch,
},
xhrFields: {
responseType: 'blob' // 设置响应类型为 blob
},
success: function(r) {
//console.log('r',r)
if(r.code==0){
Layer.alert(r.msg);
return false;
}
// 创建一个隐藏的 <a> 元素来触发下载
var a = document.createElement('a');
a.href = window.URL.createObjectURL(r);
a.download = batch+'-'+datetime()+'.xlsx'; // 设置文件名
document.body.appendChild(a);
a.click();
a.remove(); // 清理
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('导出失败:', textStatus, errorThrown);
}
});
});
/**
* 获取当前日期时间
* */
function datetime() {
const now = new Date(); // 创建一个新的 Date 对象
const year = now.getFullYear(); // 获取年份
const month = now.getMonth() + 1; // 加1使月份从1开始 获取月份(注意:返回值是从0开始计数的,即0表示1月)
const date = now.getDate(); // 获取日期
const hours = now.getHours(); // 获取小时
const minutes = now.getMinutes(); // 获取分钟
const seconds = now.getSeconds(); // 获取秒
// 格式化输出
function padZero(num) {
return num < 10 ? '0' + num : num;
}
const formattedDate = `${year}${padZero(month)}${padZero(date)}${padZero(hours)}${padZero(minutes)}${padZero(seconds)}`;
return formattedDate;
}