通過ajax調用php下載文件我有個按鈕onclick它將調用一個Ajax函數。這是我的Ajax函數function csv(){
ajaxRequest = ajax();//ajax() is function that has all the XML HTTP Requests
postdata = "data=" + document.getElementById("id").value;
ajaxRequest.onreadystatechange = function(){
var ajaxDisplay = document.getElementById('ajaxDiv');
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("POST","csv.php",false);
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxRequest.send(postdata);}我根據用戶輸入創建CSV文件。創建之后,我希望它能夠迅速下載或強制下載(最好是強制下載)。我在php文件末尾使用下面的腳本下載該文件。如果我在一個單獨的文件中運行這個腳本,它可以正常工作。$fileName = 'file.csv';$downloadFileName = 'newfile.csv';if (file_exists($fileName)) {
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.$downloadFileName);
ob_clean();
flush();
readfile($fileName);
exit;}echo "done";但是,如果我在csv.php末尾運行它,它就會將file.csv的內容輸出到頁面(到ajaxDiv中),而不是下載。有沒有辦法強制下載csv.php末尾的文件?
3 回答

精慕HU
TA貢獻1845條經驗 獲得超8個贊
$('.act_download_statement').click(function(e){ e.preventDefault(); form = $('#my_form'); form.submit();});
Content-Type
- 3 回答
- 0 關注
- 584 瀏覽
添加回答
舉報
0/150
提交
取消