jquery ajax调用后如何将文件输出到浏览器
我在网站上有一个 php 文件的链接,该文件在飞蚁上生成本机 excel 文件,通过标头将其直接输出到浏览器,供用户打开/保存。由于生成文件需要一些时间,我想使用 jQuery Ajax 进行调用并同时使用一些加载动画。
我唯一不确定如何做的是如何在 Ajax 调用后将文件输出到浏览器中?有可能吗?
I have a link on the website to a php file that generates native excel file on a fly ant outputs it directly to browser via headers for user to to open/save. Since it takes some time for the file to be generated I'd like to use jQuery Ajax to make the call and use some loading animation in the mean while.
The only thing I'm not sure how to do is how to output the file into the browser after Ajax call? Is it even possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
(NB 这是 @dmitry 答案的释义,但只是详细说明)
您遇到的问题是,无法通过 AJAX 直接将文件返回给用户 - 浏览器必须请求文件使用正常的同步 HTTP 请求。
要解决此问题,您的 PHP 将需要:
file_put_contents()
或类似方法)。您的 JS 在收到此响应后将需要:
window.open()
在新选项卡/窗口中打开 Excel 文件(或通过设置location.href
在当前选项卡/窗口中重定向)。(N.B. This is a paraphrasing of @dmitry's answer, but just elaborated upon)
The problem you have is that there is no means of directly returning a file to the user via AJAX - the browser has to request the file using a normal, synchronous HTTP request.
To solve this, your PHP will need to:
file_put_contents()
or similar).Your JS, on receiving this response will then need to:
window.open()
(or redirect in the current tab/window by settinglocation.href
).我认为你可以做一个技巧:在 Ajax 响应中生成文件并返回生成文件的路径,然后
也可以使用 iframe Ajax 调用一些技术
I think you can make a trick: generate file and return path to generated file in your Ajax response and then just call
also there some techniques with iframe Ajax
为什么不使用 iframe 来加载生成 excel 文件的实际 php 文件?这样,在生成文件时就不会阻止 UI,并且浏览器将触发下载对话框。
您无法通过 JavaScript 发送文件,至少不能以强制浏览器打开下载对话框的方式发送文件。
Why don't you use iframe where you load the actual php file that generates the excel file? That way you won't block the UI while the file is being generated and browser will trigger download dialog.
There's no way that you can send a file via javascript, at least not in the manner of forcing the browser to open the download dialog.