0

I have a Rails 4 form that is submitted via ajax by using :remote => true. The response is JSON. I get redirected to a new page with the JSON instead of being left on the current page. Why does this happen?

The form:

<%= 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 %>

The controller:

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

1 回答 1

1

You can't directly upload files via AJAX

5.2 Dealing with Ajax Unlike other forms making an asynchronous file upload form is not as simple as providing form_for with remote: true. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.

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

Edit:

You might want to take a look at: https://github.com/JangoSteve/remotipart see: form_tag with remote: true does not make an ajax request

于 2013-11-11T22:44:27.560 回答