AJAX调用后强制下载AJAX

2023-09-10 21:23:28 作者:糖果の布丁

我有一个PHP脚本,正在等待Ajax调用在

I have a php script that is waiting for ajax calls at

www.mydomain.com/file.php

www.mydomain.com/file.php

AJAX调用包含一些变量,该为file.php将用它来生成一些CSV结果,

The ajax call contains some variables, that the file.php will use to generate some csv results,

有没有可能让用户能够下载由为file.php产生的CSV内容,而不必在某个地方保存在服务器之类的东西呢?

Would it be possible for the user to be able to download the csv content produced by file.php without having to save it somewhere on the server and stuff?

我不希望将用户重定向到任何其他网页要么,我想他们点击一个按钮,然后看到下载对话框,并让他们下载csv文件。

I don't want to redirect the user to any other page either, I want them to click a button then see the download dialog, and let them download the csv file.

推荐答案

把元素的形式,并利用他们只是似乎哈克,并使用它,我觉得不舒服。

Putting elements in a form and submitting them just seems to hacky, and I don't feel comfortable using it.

当你使用这些类型的东西,我认为你是冒着一点,浏览器的下一个版本可能根本不支持。

When you are using these types of things I think you are risking a bit, the next versions of browsers may simply not support them.

此外,我想过去复杂的阵列在我的Ajax调用服务器选项,而这并不容易将它们全部转换成HTML表单,除非我在一个隐藏的元素序列化的阵列和反序列化是在服务器端,但这一切都太复杂了。

Besides I am passing complicated arrays as options in my ajax call to the server, and it's not easy to convert them all into an html form, unless I serialize the arrays in a hidden element and unserialize it on the server side, but that's all too complex.

我所做的,而不是是,当AJAX调用时,服务器存储会话中的输出,则返回的唯一密钥的值时,服务器上的另一个页面会自动回显输出的键时给出以它作为输入

What I did instead was, when the ajax call is made, the server stores the output in a session, then it returns a unique key for that value, another page on the server will simply echo the output when that key is given to it as an input,

所以,用户点击的东西,那么一个Ajax调用时,那么,在一个会话,然后用户点击一个下载链接,然后在服务器删除该会话的服务器存储。

So user clicks on something, then an ajax call is made, then the server stores that in a session, then user clicks on a download link and then the server removes that session.

这可能不是最完美的解决方案,特别是由于用户点击两次,但它只是似乎更标准给我。

It may not be the most perfect solution specially since the user has to click twice, but it just seems more standard to me.