如何使用 PHP 通过 AJAX 调用将 CSV 文件发送给用户?
我有一个 PHP 文件 dataAPI.php
,它返回一个数据数组,该数组要么序列化为 JSON,要么(正如我正在尝试实现的)CSV。 dataAPI.php
仅通过 AJAX 调用进行访问,到目前为止,它对于 JSON 数据运行良好。
问题是,我还想在客户端有一个导出按钮,单击该按钮后,将发送另一个 AJAX 调用以返回以 CSV 格式序列化的相同数据。我知道我无法通过 AJAX 发送文件,那么我该怎么做呢?
我考虑过在服务器端创建 CSV 文件,然后发送重定向 URL 作为对我的 AJAX 请求的响应。如果我这样做,如何防止两个请求覆盖彼此的文件并删除已访问/旧的 csv 文件?有更好的办法吗?任何帮助表示赞赏。
I have a PHP file dataAPI.php
which returns an array of data that is either serialized as JSON or (as I'm trying to implement) CSV. dataAPI.php
is accessed exclusively through AJAX calls, which has worked fine so far with JSON data.
The problem is, I want to also have an export button on the client-side, which when clicked, would send another AJAX call to return the same data serialized in the CSV format. I know I can't send files over AJAX, so how would I go about doing this?
I've thought of creating CSV files on the server side, and then sending a redirect-url as the response to my AJAX request. If I did this though, how could I prevent two requests overwriting each others files and remove already accessed/old csv files? Is there a better way? Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试在任一情况下返回 JSON,但 CSV 版本将返回具有一个值的 JSON 对象 - 包含 CSV 数据的长字符串。
You could try returning JSON in either case, except that the CSV version would return a JSON object that has one value - a long string containing the CSV data.
1) 对于 AJAX 调用,在服务器上的某个位置创建文件并发回一个链接 - 然后可以将该链接重定向到(例如在子窗口中),或单击...
2) 防止数据被不同的数据覆盖请求,在服务器端创建一个唯一的文件名(例如使用 uniq_id() 函数)。您仍然可以使用带有 header() 标记的相同文件名发送它们。一旦确定不再需要这些文件,请确保删除它们(我个人使用如下的内务管理脚本:
1) For the AJAX call, create the file somewhere on the server and send a link back - this link can then be either redirected to (e.g. in a subwindow), or clicked on...
2) To prevent data being overwritten by different requests, create an unique filename server-side (e.g. with the uniq_id() function). You can still send them with the same filename with a header() tag. Make sure you delete those files once you are sure you no longer need them (I personally use a housekeeping script like the following:
您可以将以下代码放入文件中,然后向其发送 xhr 请求以调用该文件。或者您可以尝试在单独的工具中打开该文件,而不需要弹出窗口。
You can put the following code in a file and then send an xhr request to it invoking the file. Or you can try opening the file in a separate tool less pop up.