2015-02-24 20 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請求。

祝你好運!