Rails通过ajax提交表单并更新视图

Pra*_* KJ 8 javascript forms ajax jquery ruby-on-rails

我想通过ajax更新表单提交而不重新加载页面并根据它更新视图.我尝试了不同的方法,并失败了作为新的rails.

这是情况.

在模态中

def new
    @new_entry = current_user.notes.build
    @words = current_user.notes
    @notes_false_list = current_user.notes.where(known: false).order("title").group_by { |note| note.title[0] }
    @notes_true_list = current_user.notes.where(known: true).order("title").group_by { |note| note.title[0] }
  end
Run Code Online (Sandbox Code Playgroud)

在视图中的表单代码.

<%= form_for @new_entry, :html => {:class => 'home-form without-entry clearfix'}  do |f| %>
      <%= f.text_field :title, placeholder: 'Squirrel', autofocus: true, class: 'title-field pull-left' %>
      <%= f.submit '', class: 'btn home-add without-entry' %>
  <% end %>
Run Code Online (Sandbox Code Playgroud)

创建动作

def create
    @new_note = current_user.notes.build(new_note_params)
    if @new_note.save
      @notes_list = current_user.notes.count
      unless @new_note.user.any_entry
        @new_note.user.toggle!(:any_entry) if @notes_list >= 50
        redirect_to root_url
      end
    else
      redirect_to root_url
    end
  end
Run Code Online (Sandbox Code Playgroud)

最后在视图中我想改变

<p class="instructions count-instruction text-center">
      <%= @words.count %>
    </p>
Run Code Online (Sandbox Code Playgroud)

花了很多时间用AJAX更新它,但每次都失败了.有没有帮助?提前致谢.

Mil*_*ind 15

你的代码很好,但对于ajax,

  1. 你需要添加remote=true到你的表单.

    <%= form_for(@image,:html=>{:id=>"your_form_id",:multipart => true,:remote=>true}) do |f |%>

  2. 此外,在您的服务器端,您需要创建一个js.erb文件 views/users/show_updated_view.js.erb以回复浏览器作为其js调用而不是html调用,因此需要向用户显示表单提交后发生的事情(成功/错误)(如果它users_controller),

所以在你的行动中,你需要这样的东西: -

        respond_to do |format|  
            format.js { render 'users/show_updated_view'}
        end  
Run Code Online (Sandbox Code Playgroud)
  1. show_updated_view.js.erb,您应该更新您的视图,以便用户知道视图已更新或表单已成功提交,方法是隐藏整个表单/重置表单或用新div替换表单,说明数据已更新.或者任何直观的东西.虽然有很多方法:).

    //这里我用div发消息替换你的整个表格

    $("#your_form_id").html("<div><p>You have submitted the form successfully.</p></div>");

视图的名称可以是任何东西,但您需要处理成功和失败.