Turbolinks 5 ajax开机自检

In my Rails 5 / Turbolinks 5 application i would like to put the html resulting from a form submission into a div.

The form is a

= form_for(user) do |f|

standard rails form.

After a successful submission a redirect is send to the browser

respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was  created.' }

when i submit the form via ajax:

$(".dialog").on("submit", "form", function(e){
 e.preventDefault();
 $.ajax({
  url: $(this).attr("action"),
  method: "POST",
  data: $(this).serialize()
 }).done(function(data) {
  $(".dialog .canvas").html(data);
 });
});

the from gets submitted and the server's redirect_to statement redirects the browser the the new user's page.

The redirect causes turbolinks to replace the body with the content of the page the browser was redirected to. instead i want to replace a specific div $(".dialog .canvas").html(data). how can i prevent this behaviour of turbolinks.

If I understand what you're trying to do properly, you can render HTML from the server and update your div element using JavaScript generated from your server.

# HTML form
<%= form_for @user, remote: true do |f| %>
  ...
<% end %>

# app/controllers/users_controller.rb
def create
  @user = User.create(user_params)
  # renders create.js.erb automatically with AJAX request (remote: true)
end

# app/views/users/create.js.erb
$("#my-div").html("<%=j render(partial: 'users/user', locals: { user: @user }) %>");

Note that in your js.erb files you can use Ruby as well as JavaScript; I find it very useful for building out HTML and dynamic content and passing it back to the client to be run as JavaScript.

Folks can discuss the pros/cons of server-generated JavaScript, but I'm of the opinion it's perfectly fine and it works well. Otherwise you have to keep server/client templates in sync, which is really messy; or you have to do all your templates client-side and only use your server for JSON.

I just don't see breaking up the client/server that way as the future, although there are a lot of people who claim that's the direction everything is going. Just look at the plethora of JavaScript MVC frameworks popping up.

With turbolinks 5.0.1, in the controller add the option turbolinks: false i.e format.html { redirect_to @user, notice: 'User was created.', turbolinks: false }

Other solution (not so good because it will not allow you to update to Rails 5.1) is to stick to turbolinks 2.5.3.

There could be other solutions by using format.js or even format.json, check: https://github.com/vtamara/turbolinks_prob50