【发布时间】:2013-10-09 16:52:58
【问题描述】:
这是 HTML:
<button name="download">Download</button>
我希望用户在单击此按钮时下载文件。为此,我使用了以下 Ajax 请求:
$parent.find('button[name=download]').click(function () {
$.ajax({
url: "download.php",
sucess: function(data, status, jqXHR){
$console.text('Download efetuado');
},
error:function(xhr, status, error){
$console.text(xhr.responseText);
}
});
});
download.php 在哪里:
if (file_exists($myFile)){
header ("Content-Type: application/json");
header ("Content-Disposition: attachment; filename=$fileName");
header("Content-Length: " . filesize("$myFile"));
$fp = fopen("$myFile", "r");
fpassthru($fp);
} else {
echo "no file exists";
};
这没有输出任何东西,也没有下载任何文件。我知道 PHP 脚本正在运行并且正在被调用。
【问题讨论】:
-
不要发送 ajax 请求。只需重定向到下载。或者更好的是,将按钮设为锚标记并删除 javascript。