如何从javascript调用rails时导出xls

时间:2017-02-12 10:19:22

标签: javascript ruby-on-rails ajax excel

我试图通过javascript调用触发excelsheet下载。 当我使用link_to按钮调用rails动作时,它工作正常。 但是当我通过js脚本调用rails动作时(我想做)我在日志中得到了相同的渲染消息但是excel没有下载。 我认为这与ajax /后台任务调用有关,但我无法弄明白。知道如何让javascript方法起作用吗?

Rails行动:

def goal_designer_spreadsheet
  @format = params[:format]
  logger.debug "\nformat = #{@format} \n"
  respond_to do |format|
    format.html 
    xls_filename = "Excel_file__abc.xls"
    format.xls {headers["Content-Disposition"] = "attachment; filename=\"#{xls_filename}\"" }
  end
end

2个按钮:1个触发JS调用(不工作),一个直接触发(工作):

<button class="btn btn-primary" id="goal_download_list">Download this Plan (.xls) javascript</button>

<%= link_to "Download this Plan (.xls) rails", plan_goal_designer_spreadsheet_path(format: "xls"), :id => "", :class => "btn btn-small btn-primary" %>

Javascript电话:

if ( trigger_object.id.match(/goal_download_list/) ) {
  $.ajax({
    type:  'get',       
    url:   "/plan/goal_designer_spreadsheet",
    data: { 
      "format":   "xls"
    },
    success: function(data, textStatus) {
    }      
  });  
}    

输出日志:两种情况都类似,但在JS调用的情况下,没有xls下载:

Rendered plan/goal_designer_spreadsheet.xls.erb (0.0ms)
Completed 200 OK in 344ms (Views: 339.9ms | ActiveRecord: 0.0ms)

1 个答案:

答案 0 :(得分:0)

进行重定向可能会更好:

window.open("plan/goal_designer_spreadsheet.xls", "_blank");