[英]Download a file built in PHP output buffer from AJAX call
我正在嘗試用PHP構建一個CSV文件,然后從AJAX調用中調用PHP文件,然后在AJAX調用成功后啟動CSV文件的下載。 如果我在服務器上保存.csv的物理副本,這可以正常工作,但我想使用php://ouput
所以我不必擔心物理文件會堵塞服務器。 是否可以從返回php://output
到AJAX啟動下載? 這是我的代碼:
HTML / jQuery的:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#download").live("click", function() {
var request = $.ajax({
dataType: 'html',
url: 'php.php',
success: function(response) {
alert('Finished');
}
})
})
</script>
</head>
<body>
<h1 id="download">DOWNLOAD</h1>
</body>
</html>
PHP:
<?php
header('Content-type: application/vnd.ms-excel');
header('Content-disposition: attachment; filename="test.csv"');
$f = fopen('php://output', 'w');
fwrite($f,'this,is,a,test');
fclose($f);
readfile('php://output');
return;
?>
我不知道如何從我的AJAX調用返回文件保存對話框。
這必須簡單,但我似乎找不到任何結合這兩個問題的例子。
您可以通過jquery創建和發送表單來執行此操作(頁面未重新加載):
$(document).on('click', '#download', function () {
var form = $(document.createElement('form'));
form.attr('action', 'php.php');
form.attr('method', 'GET');
form.appendTo(document.body);
form.submit();
form.remove();
});
如果需要,您也可以傳遞post參數:
$(document).on('click', '#download', function () {
var form = $(document.createElement('form'));
form.attr('action', 'php.php');
form.attr('method', 'POST');
var input = $('<input>').attr('type', 'hidden').attr('name', 'x').val('x value');
form.append(input);
form.appendTo(document.body);
form.submit();
form.remove();
});
以下工作,但非常有用,因為它調用php.php文件兩次。 有沒有人有更好的想法?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#download").live("click", function() {
var request = $.ajax({
dataType: 'html',
url: 'php.php',
success: function(response) {
window.open('php.php');
}
})
})
</script>
</head>
<body>
<h1 id="download">DOWNLOAD</h1>
</body>
</html>
反正只是為這個實例緩存'php.php',以便它在window.open('php.php')
下立即加載,但是當我點擊下一步download
時會重新加載內容嗎?
為什么window.open(response)
不能正常工作?
看看這個:
if (!headers_sent()) {
// seconds, minutes, hours, days
$expires = 60*60*24*14;
header('Pragma: public');
header('Cache-Control: maxage=' . $expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
}
注意:這不適用於POST請求,只需要GET。
要允許文件下載,您只需調用以下代碼(例如,在按鈕的onclick上):
window.open(<file-url>);
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.