Javascript 如何在AJAX调用后下载文件
如何在AJAX调用后自动下载文件?现在,我的AJAX调用将我重定向到资源,而不是下载文件 这是我的AJAX调用:Javascript 如何在AJAX调用后下载文件,javascript,jquery,ajax,Javascript,Jquery,Ajax,如何在AJAX调用后自动下载文件?现在,我的AJAX调用将我重定向到资源,而不是下载文件 这是我的AJAX调用: $('.download').click(function (e) { e.preventDefault(); let videoId = $('#video').data('video-id'); $.ajax({ url: "/video/" + videoId + "/download-link", type: "GET"
$('.download').click(function (e) {
e.preventDefault();
let videoId = $('#video').data('video-id');
$.ajax({
url: "/video/" + videoId + "/download-link",
type: "GET",
success: function (response) {
window.location = response.link;
}
});
});
这是html标记:
<a href="#" class="download">
<i class="fas fa-long-arrow-alt-down"></i>Download
</a>
因为您正在通过window.location手动重定向它。若你们有资源链接,有多种方式下载文件。其中之一是使用下载属性。此外,在将同一问题作为新问题发布之前,您也可以尝试搜索该问题是否已经存在。 您可以在此处找到详细答案:
您应该做的是确保服务器使用以下文件url头进行响应
Content-Disposition: attachment; filename="file-name" // file name is not required, and can be ommitted
// This will make browsers understand that this is a downloadable resource
然后在ajax中执行此操作
...
window.open(response.link, '_blank');
点击下载链接后会得到什么?重定向到文件urlshow你的php代码?php代码返回一个URL,那里没有问题