2015-02-24 36 views
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 

回答

1

恐怕你无法通过AJAX下载文件。为此,您应该尝试执行单独的请求。

尝试发送参数作为表单提交(因为您的操作控制器期望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请求。

祝你好运!