简体   繁体   English

使用JQuery触发浏览器下载

[英]Trigger a browser download with JQuery

My goal is to let a user download a PDF from my server. 我的目标是让用户从我的服务器下载PDF。 The most common approach to this would be to simply have a link with a download attribute like so 最常见的方法是像这样简单地拥有一个带有下载属性的链接

<a href="http://mysource.pdf" download>click here</a>

The problem with this is that I cannot monitor the download or have a callback when it is finished. 这样做的问题是我无法监视下载或完成下载时出现回调。 The browser just hangs until the request is processed and suddenly pops up a download when it is done. 浏览器将一直挂起,直到处理完请求为止,并在完成后突然弹出下载。 So now I am getting pdf data from a server with AJAX and want to download the data via the browser. 因此,现在我正在使用AJAX从服务器获取pdf数据,并希望通过浏览器下载数据。
So I have something along the lines of 所以我有一些类似的东西

$.get("http://mysource.pdf", (data) ->
  #need to somehow trigger a download with this data
)

I've been searching for a while to no avail. 我一直在寻找无济于事。 Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

--edit To clarify why this is not a duplicate, I am asking about triggering a download on data, not a local file. --edit为了弄清为什么它不是重复的,我询问触发数据下载,而不是本地文件下载。

$('a').click(function(event) {
    event.preventDefault();  
    $.get("http://mysource.pdf", (data) ->
      window.location.href = $(this).attr('href');
    )

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM