问题描述:

I am trying to export a csv file with some data. I am making an ajax call after selecting some of the rows from the view table (jqGrid) and exporting it in a csv format. The issue is after successful ajax call, the filtered data is appearing as an alert message not as a download option?? any ideas??

View Code:

 function x() {

var obj = jQuery("input:checked").map(function() { return jQuery(this).parents('tr').attr('id'); });

var arr = jQuery.makeArray(obj);

var data = arr.join(',');

$.ajax({

url : '<%= url_for :action => "export_to_csv" %>',

type : 'POST',

data : {data:data},

dataType : 'json',

success : function(response) {

alert("Details saved successfully!!!");

},

error : function (request, status, error) {

alert(request.responseText);

}

});

}

controller code:

def export_to_csv

require 'fastercsv'

data = params['data'].split(',')

@gos = GoSe.find(:all, :conditions => [ "id IN (?)", data])

csv = FasterCSV.generate do |line|

cols = ["ID","Details","PartnerCode","Sece","Date","Partner","Person","TaxName","TaxID"]

line << cols

@gos.each do |entry|

line << [entry.id, entry.description, entry.code, entry.ellipsis, entry.oDate, entry.name, entry.people_name, entry.tax_name, entry.tax_id ]

end

end

send_data(csv,

:type => 'text/csv; charset=iso-8859-1; header=present',

:disposition => "attachment; filename=go_data_#{Time.now.strftime('%d-%m-%y--%H-%M')}.csv")

end

网友答案:

With the following update in the code..its working..Try it out!!

function x() {

var obj = jQuery("input:checked").map(function() { return jQuery(this).parents('tr').attr('id'); });

var myAjaxVariable = null;
var arr = jQuery.makeArray(obj);
var data = arr.join(',');


$.ajax({
 url : '<%= url_for :action => "export_to_csv" %>',
 type : 'POST',
 data : {data:data},
 dataType : 'json',
 async : false,
     success : function(response) {myAjaxVariable = response;},
     error : function (request, status, error) {
            alert(request.responseText);
        }       
  });   

window.open( "data:text/csv;charset=utf-8," + escape(myAjaxVariable))  


}
相关阅读:
Top