简体   繁体   English

使用ajax下载文件

[英]Using ajax to download a file

I have a javascript file that uses ajax and passes an array of ids to a rails controller action. 我有一个使用ajax的javascript文件,并将ID数组传递给Rails控制器操作。 The controller then maps these to model objects and generates a file containing some of their data. 然后,控制器将这些映射到模型对象,并生成一个包含其中一些数据的文件。 My problem lies in downloading this file. 我的问题在于下载此文件。

Before, I was saving the needed objects in the database first, and then the controller could just format as .ics, call the same action, then the file would be downloaded. 之前,我先将所需的对象保存在数据库中,然后控制器可以将其格式化为.ics,调用相同的操作,然后下载文件。

Now everything is more dynamic, and I'm having trouble rendering the file now that I have to pass in params. 现在,一切都变得更加动态了,由于必须传递参数,因此无法渲染文件。 Is there a way to do this? 有没有办法做到这一点? I've tried 我试过了

render :layout => false, :text => @calendar.to_ical

and

send_data @calendar.to_ical, :type=> 'text/ics'

and

render :text => @calendar.to_ical

All of which complete successfully, but no file is ever downloaded. 所有这些都成功完成,但是从未下载任何文件。

Any help would be appreciated! 任何帮助,将不胜感激! Thank you! 谢谢!

The short answer is you cannot use AJAX to download files (for security reasons). 简短的答案是您不能使用AJAX下载文件(出于安全原因)。 Check out this question for other options, like setting window.location= or using the jQuery File Download plugin. 请查看此问题以了解其他选项,例如设置window.location=或使用jQuery File Download插件。

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

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