通过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 回答
catspeake
TA贡献1111条经验 获得超0个赞
$('.act_download_statement').click(function(e){ e.preventDefault(); form = $('#my_form'); form.submit();});
Content-Type
添加回答
举报
0/150
提交
取消