我需要通过ajax请求成功下载文件。我编写了如下所示的ajax代码。在控制器中处理ajax请求。它发送数据。但是,我认为这是一个警告。我也把性格放进去。它可以转换,但无法下载。
有人能帮我解决这个问题吗?
Ajax:
email_download_file = function(id, email) {
if(id !== null){
$('#customButton').attr('disabled','disabled');
var jqxhr = $.post('/orders/csv/download', {
email: email,
emaillist_type: $('#emaillist_type').val(),
nrecords: $('#no_of_records_selected').val()
}).done(function(data) {
alert(data);
}).fail(function() {
$('#customButton').removeAttr('disabled');
alert("There was a problem with us receiving your data. Please refresh this page and try again. Or contact us at support@onegoodemail.org. We're sorry this happened! :(");
}).always(function() {
});
}
}
控制器:
def order_download
begin
email = params[:email]
emaillist_type = params[:emaillist_type]
num_records = params[:nrecords]
email_records = EmailList.where(emaillist_type: emaillist_type).limit(num_records.to_i)
send_data email_records.to_csv, type: "text/csv; charset=iso-8859-1; header=present", disposition: "attachment;filename=#{emaillist_type}.csv"
rescue Exception => e
render :nothing, status: 401
end
end
型号:
def self.to_csv
CSV.generate do |csv|
csv << ["First Name","Last Name","Designation","Email","Industry","Company Name","Website","City","Country"]
all.each do |l|
csv << [l.firstname,l.lastname,l.designation,l.email,l.industry,l.company_name,l.website,l.city,l.country]
end
end
end
恐怕您无法通过ajax下载文件。为此,您应该尝试执行单独的请求。
尝试将params作为表单提交发送(因为您的操作控制器需要POST请求)。也许在你看来是这样的?
<form action="/orders/csv/download" target="_blank">
<input type="hidden" name="email" value="..." />
<input type="hidden" name="emaillist_type" value="..." />
<input type="hidden" name="nrecords" value="..." />
</form>
你注意到我在form
标签中使用了target="_blank"
吗?这可能会给人留下这样的印象,即请求是异步执行的,这与您尝试实现的效果相去甚远,但这是您可以开始的!
若你们真的想坚持AJAX之类的下载文件,也许这是你们可以尝试的东西?(https://stackoverflow.com/a/9970672/4381282-PS。我自己还没有试过,但这似乎很合理!)不过,我不确定它是否支持POST
请求。
祝你好运!