我有一個按鈕和onclick
它會調用ajax函數。通過ajax調用下載文件php
這裏是我的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結束?
我認爲在技術上是最好設置'window.location';看到這個討論:http://stackoverflow.com/questions/7857878/window-location-vs-document-location – yitwail