我有一个按钮,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的最后一个文件?
window.location
进行设置;请参考此讨论:http://stackoverflow.com/questions/7857878/window-location-vs-document-location - yitwail