Rails turbolinks 中断提交远程表单 [英] Rails turbolinks break submit remote form
问题描述
我在使用 Rails 4、Turbolinks 和远程表单时遇到了一个相当奇怪的问题.我有一个看起来像这样的表格:
I'm having a rather weird problem using Rails 4, Turbolinks and a remote form. I have a form looking like:
<%= form_for [object], remote: true do |f| %>
<td><%= f.text_field :name, class: 'form-control' %></td>
<td><%= f.email_field :email, class: 'form-control' %></td>
<td><%= f.submit button_name, class: 'btn btn-sm btn-primary' %></td>
<% end %>
此表单添加(创建)一个新对象.然而,它并不总是有效:
This form adds (creates) a new object. It does however not always work:
- 当我直接使用 URL 或刷新加载页面时;它有效
- 当我从我的应用导航到这个页面时;它失败了
当为此链接禁用 Turbolinks 时,页面运行良好.
When disabling Turbolinks for this link, the page worked perfectly.
我有两个问题:
- 为什么这不起作用?这是因为 JQuery/Turbolinks 问题导致远程处理程序未附加到按钮吗?
- 我该如何解决这个问题?
提前致谢.
解决方案
感谢@rich-peck,解决方案是添加一段javascript,在单击按钮时手动提交表单:
Thanks to @rich-peck, the solution was to add a piece of javascript that manually submits the form upon clicking the button:
<%= javascript_tag do %>
var id = "#<%= dom_id(f.object) %>";
var inputs = $(id).parent().find('input');
console.log(inputs);
$(id).parent().find('button').on('click', function(e) {
e.preventDefault();
$(id).append(inputs.clone());
$(id).submit();
});
<% end %>
此代码将 javascript 添加到表单表行,获取输入,将它们附加到 ID 并提交表单.preventDefault();防止在页面刷新并且表单实际工作时查询被发送两次.
This code adds javascript to the form table row, getting the inputs, appending them to the ID and submitting the form. The preventDefault(); prevents the query from getting sent twice when the page is refreshed and the form actually works.
推荐答案
Turbolinks
如前所述,Turbolinks 的问题在于它使用 ajax 调用重新加载 DOM 的 <body>
部分 - 这意味着 JS 没有重新加载,因为它在头部
As mentioned, the problem with Turbolinks is that it reloads the <body>
part of the DOM with an ajax call - meaning JS is not reloaded, as it's in the head
解决这个问题的典型方法是delegate
document
中的 JS,如下所示:
The typical way around this issue is to delegate
your JS from the document
, like this:
$(document).on("click", "#your_element", function() {
//your code here
});
因为document
会一直存在,所以会不断触发JS
Because document
is always going to be present, it will trigger the JS continuously
远程
你的问题有点棘手
问题是您依赖于 JQuery UJS Rails 的 (unobtrusive JavaScript) 引擎,难以自行补救
The problem is you're relying on the JQuery UJS (unobtrusive JavaScript) engine of Rails, which is difficult to remedy on its own
我们从来没有遇到过这个问题&我们一直在使用 Turbolinks - 所以我想问题可能在于您如何构建表单/处理请求.这个 GitHub 似乎重现了这个问题,与表格有关
We've never had this issue & we use Turbolinks all the time - so I suppose the problem could be with how you're constructing your form / handling the request. This GitHub seemed to recreate the issue, and it was to do with the table
也许你可以试试:
<%= form_for [object], remote: true do |f| %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.email_field :email, class: 'form-control' %>
<%= f.submit button_name, class: 'btn btn-sm btn-primary' %>
<% end %>
这篇关于Rails turbolinks 中断提交远程表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!