1 回答

TA貢獻1797條經驗 獲得超6個贊
實際上,您不能使用 Ajax 下載文件,當您使用 PHP 創建 excel 文件時,您是在服務器端創建它,您必須要求服務器下載它。因此,如果您想下載它,您可以做一個小技巧,使用您剛剛使用 PHP 創建的文件的 URL 創建一個隱藏的錨鏈接,并在 ajax 返回成功時單擊它。
這是一個錨鏈接的例子,把它放在html視圖上。
<a href="replace_src_of_the_file" download id="hiddenDonwloader" hidden></a>
這是 Ajax 的一個示例。當您達到“成功”意味著文件已成功創建時,您可以確保下載它。如果您之前不知道文件名,那么您也可以返回文件名并在“成功”中獲取它并在單擊之前更改href屬性。
$.ajax({
headers: {
// Put your headers here
_your_header_
},
url: url_of_php, // put your url here
type: 'POST',
dataType: 'text',
data: {
datos: data // put your data to send here
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
},
success: function (data) {
//Here we click the anchor link be sure that the href attribute is right
document.getElementById('hiddenDonwloader').click();
},
});
希望有幫助!
- 1 回答
- 0 關注
- 178 瀏覽
添加回答
舉報