远程:通过Jquery提交后,true无效

时间:2018-04-14 04:33:43

标签: ruby-on-rails ruby

我通过Jquery提交带有复选框的表单,远程为true,但它不起作用。它一直在控制器中呈现html格式,我可以找出原因。

这是我的提交按钮和表单:

<%= button_to "Read sel", root_path, class: "btn btn-info btn-sm padlr", id: "notification-submit" %>

<%= form_tag read_selected_notifications_path, :authenticity_token => true, remote: true ,id: "notification-form" do %>
  <% @notifications.each do |x| %>
    <div class="notification-body flerowspb">
      <div class="flerowspb" style="width:80%">
        <div class="notif-check flecolcen">
          <%= check_box_tag "read_notif[]", value="#{x.id}" %>
        </div>
        <div class="notif-details ">
          <div class="notif-time flerowspb">
            <% if !x.viewed %>
               <span class="glow"> New  <%= x.notification_type.capitalize %></span>
            <% else %>
               <span><span class="text-grey"> New <%= x.notification_type.capitalize %></span></span>
             <% end %>
             <span class="text-grey font-small"> <%= time_ago_in_words(x.created_at) %> ago</span>
          </div>
          <div class="notif-body font-medium text-grey">
            <span class="text-blue"><%= link_to x.sender.username, profile_path(x.sender) %> </span>  <%= x.title %>  <br>
            Click <span class="text-blue"><%= link_to "Here", entry_path(x.entry_id, notification_id: x.id) %> </span> to view it
          </div>
        </div>
      </div>
      <div class="notif-image">
        <%= image_tag x.entry.image.small_thumb %>
      </div>
    </div>
  <% end %>
<% end %>

因此表格没有实际的提交按钮,因为我希望表单上方的按钮不是这样的,

enter image description here

我知道我必须添加:authenticity_token => true,因为rails并未将此form_tag添加到remote: true

这是我的控制器:

def read_selected
  Notification.read_selected(current_user.id, params[:read_notif])
  respond_to do |format|
    format.html{
      flash[:success] = "Selected notifications marked as read"
      redirect_to notifications_path
    }
    format.js{
      render 'notifications/jserb/read_selected'
    }
  end
end

这是js代码:

$(document).on('turbolinks:load', function(){
  if (window.location.href.match(/\/notifications/)) {
    $('#notification-submit').on('click', function(e){
      console.log('oisdjfilds');
      e.preventDefault();
      $('#notification-form').submit();
    });
  }
});

编辑:我在表单底部的提交按钮中添加了它应该正常工作,所以这与我提交表单的方式有关

1 个答案:

答案 0 :(得分:1)

我假设你正在使用Rails 5,因为它的行为存在这样的不一致。请查看issue

据我所知,问题的快速解决方案将是:

  1. 获取表单HTML元素:

    form = document.getElementById('notification-form');
    

    form = $('#notification-form')[0]
    
  2. 然后触发Rails submit

    Rails.fire(form, 'submit');
    

    form.dispatchEvent(new Event('submit', {bubbles: true}));