0
我需要通过ajax请求成功下载文件。我写下如下所示的ajax代码。处理控制器中的ajax请求。它发送数据。但是,我看到了一个警报。我也把性格。它转换但无法下载。如何通过rails中的ajax获取csv文件
任何人都可以帮助我解决这个问题吗?
阿贾克斯:
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 [email protected] 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