Rails 4 - 提交ajax表单但正在重定向页面

时间:2013-11-11 22:25:45

标签: ruby-on-rails ajax ruby-on-rails-4

我有一个Rails 4表单,使用:remote => true通过ajax提交。响应是JSON。我被重定向到一个带有JSON的新页面,而不是留在当前页面上。为什么会这样?

表格:

<%= form_tag(
    {:controller => :uploads, :action => :create}, 
    :remote => true,
    :authenticity_token => true,
    multipart: true, 
    class: "hidden",
    id: "uploadDataForm") do %>
  <%= file_field_tag :file, class: "btn btn-primary btn-lg", style: "width: 100%;" %>
  <%= submit_tag "Upload CSV", class: "btn btn-success btn-lg disabled" %>
<% end %>

控制器:

class UploadsController < ApplicationController
  def create
    @test = "hello"
    render json: @test
  end
end

1 个答案:

答案 0 :(得分:1)

您无法通过AJAX直接上传文件

  

5.2处理Ajax   与其他表单不同,制作异步文件上传表单并不像使用remote:true提供form_for那么简单。使用Ajax表单,序列化是通过在浏览器内运行的JavaScript完成的,因为JavaScript无法从硬盘驱动器读取文件,所以无法上载文件。最常见的解决方法是使用不可见的iframe作为表单提交的目标。

http://guides.rubyonrails.org/form_helpers.html#uploading-files

编辑:

你可能想看看: https://github.com/JangoSteve/remotipart 看到: form_tag with remote: true does not make an ajax request