?Briella 2017-02-03 21:04 采纳率: 0%
浏览 27

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.

  • 写回答

2条回答 默认 最新

  • Memor.の 2017-03-11 00:17
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试