1 回答
TA贡献1797条经验 获得超6个赞
实际上,您不能使用 Ajax 下载文件,当您使用 PHP 创建 excel 文件时,您是在服务器端创建它,您必须要求服务器下载它。因此,如果您想下载它,您可以做一个小技巧,使用您刚刚使用 PHP 创建的文件的 URL 创建一个隐藏的锚链接,并在 ajax 返回成功时单击它。
这是一个锚链接的例子,把它放在html视图上。
<a href="replace_src_of_the_file" download id="hiddenDonwloader" hidden></a>
这是 Ajax 的一个示例。当您达到“成功”意味着文件已成功创建时,您可以确保下载它。如果您之前不知道文件名,那么您也可以返回文件名并在“成功”中获取它并在单击之前更改href属性。
$.ajax({
headers: {
// Put your headers here
_your_header_
},
url: url_of_php, // put your url here
type: 'POST',
dataType: 'text',
data: {
datos: data // put your data to send here
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
},
success: function (data) {
//Here we click the anchor link be sure that the href attribute is right
document.getElementById('hiddenDonwloader').click();
},
});
希望有帮助!
- 1 回答
- 0 关注
- 188 浏览
添加回答
举报
