通过 JQuery AJAX 下载无法正常工作
我想使用 jQuery 通过 post 请求使用 ajax 下载文件。
这是我正在使用的 PHP 代码。
if (file_exists($file)) {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
}
这就是 jQuery。
$('button.erp_ci_download').click(function(){
var formData = $('form#erp_customerinvoice').serialize();
$.ajax({
type: 'POST',
url: "App/Ajax/Excel/Download.php",
data: formData
});
});
难道这样就不能下载了吗?我尝试谷歌搜索,有些人建议这和我做的方式一样。但在我的控制台中,它显示了一些垃圾值作为响应。
我哪里出错了?
谢谢..
i want to download a file using ajax via post request using jQuery.
here is the PHP code i am using.
if (file_exists($file)) {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
}
and this is the jQuery.
$('button.erp_ci_download').click(function(){
var formData = $('form#erp_customerinvoice').serialize();
$.ajax({
type: 'POST',
url: "App/Ajax/Excel/Download.php",
data: formData
});
});
is it not possible to download it this way? i tried googling and some suggested it is the same way i am doing it. but in my console it shows some garbage values as response.
where am i going wrong?
thank you..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以简单地将 POST 请求发送到您的
App/Ajax/Excel/Download.php
页面,其中包含您想要的表单数据,而无需使用 jQuery 的 AJAX。如果您的响应标头正确,当您发布“erp_customerinvoice”表单时,默认情况下浏览器将向您显示一个下载文件对话框,并且您将永远不会导航到 Download.php 页面,因为响应标头将阻止重定向。请参阅一些相关问题以获取更多说明和替代方案:
You could simply send a POST request to your
App/Ajax/Excel/Download.php
page with the form data you wish and forget about using jQuery's AJAX. If your response headers are correct, when you post your "erp_customerinvoice" form, the browser will, by default, show you a download file dialog and you will never navigate to the Download.php page because the response headers will prevent a redirect.See some related questions for more explanation and alternatives: