【发布时间】:2023-04-04 19:07:01
【问题描述】:
我正在编写 PHP 代码(在 drupal 中)以使用 ajax 将数据导出到 excel 文件我没有收到任何错误,但是当我单击按钮导出到 excel 时文件没有下载。 但是当我直接加热 url(来自浏览器)时,文件会被下载
这是ajax代码
jQuery('.export-csv', context).once('export').click(function() {
console.log('test');
var role = 'teacher';
/*get basepath*/
var basepath = drupalSettings.path.baseUrl;
jQuery.ajax({
type : 'GET',
url : basepath + 'report-export/'+role,
success : function (data) {
console.log('success');
},
error: function () {
console.log('error');
}
})
})
和控制器中的php函数下载excel文件
public function exportToExcel($role)
{
$filename = "report.xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
$records = array(
'0' => array('Name'=> 'user1', 'Status' =>'complete', 'Priority'=>'Low', 'Salary'=>'001'),
'1' => array('Name'=> 'user2', 'Status' =>'inprogress', 'Priority'=>'Low', 'Salary'=>'111'),
'2' => array('Name'=> 'user3', 'Status' =>'hold', 'Priority'=>'Low', 'Salary'=>'333'),
'3' => array('Name'=> 'user4', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'444'),
'4' => array('Name'=> 'user5', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777'),
'5' => array('Name'=> 'user6', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777')
);
$heading = false;
if(!empty($records))
foreach($records as $row) {
if(!$heading) {
// display field/column names as a first row
echo implode("\t", array_keys($row)) . "\n";
$heading = true;
}
echo implode("\t", array_values($row)) . "\n";
}
exit;
}
虽然我没有收到错误但文件没有下载。并且在 ajax 控制台中也收到成功消息。当我直接点击网址时
site.com/report-export/ 文件被下载
【问题讨论】: