在 public/js 檔案中,我請求 $ajax,并得到回應只是字串,而不是檔案。
如果客戶端使用 ajax 發送請求,服務器將使用字串而不是 xlsx 檔案進行回應。
這是請求部分:
$("#downloadXLS").on('click', function () {
$.ajax({
type: 'get',
url: appRoot "transactions/downloadXLS/",
success: function () {
},
error: function () {
}
});
});
這是php回應函式:
public function downloadXLS()
{
// Filter the excel data
function filterData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if (strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// Excel file name for download
$fileName = "transaction-data_" . date('Y-m-d') . ".xls";
// Column names
$fields = array('No.', 'Pay Date', 'Company');
// Display column names as first row
$excelData = implode("\t", array_values($fields)) . "\n";
// Headers for download
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$fileName\"");
$allTranscations = $this->transaction->getAll();
if (is_array($allTranscations)) {
// Output each row of the data
foreach ($allTranscations as $key => &$trans) {
$lineData = array($key 1, $trans->pay_time, $trans->company);
array_walk($lineData, 'filterData');
$excelData .= implode("\t", array_values($lineData)) . "\n";
}
} else {
$excelData .= 'No records found...' . "\n";
}
// Render excel data
echo $excelData;
exit();
}

uj5u.com熱心網友回復:
您無法通過 ajax 請求下載檔案。試試 location.href=transactions/downloadXLS。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/464415.html
