Tôi có một nút và onclick
nó sẽ gọi một hàm ajax.Tải tập tin qua một cuộc gọi ajax php
Đây là chức năng ajax tôi
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);
}
tôi tạo ra các tập tin csv dựa trên đầu vào người dùng. Sau khi nó được tạo ra tôi muốn nó để tải về tải về hoặc lực lượng tải về (tốt nhất là lực lượng). Tôi đang sử dụng tập lệnh sau ở cuối tệp php để tải xuống tệp. Nếu tôi chạy tập lệnh này trong một tệp riêng biệt thì nó hoạt động tốt.
$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";
Nhưng nếu tôi chạy nó vào cuối csv.php, nó sẽ xuất nội dung của tệp.csv vào trang (vào ajaxDiv) thay vì tải xuống.
Có cách nào để buộc tải xuống tệp ở cuối csv.php không?
Tôi tin rằng về mặt kỹ thuật nó tốt hơn để thiết lập 'window.location'; xem thảo luận này: http://stackoverflow.com/questions/7857878/window-location-vs-document-location – yitwail