Goal
我有一个包含来自 Rails 后端的项目列表的页面。我希望能够通过 Rails UJS 使用 Ajax 调用来编辑该列表中的一行。
Approach
我在每行的末尾添加了一个编辑按钮。编辑按钮是一个link_to ... :remote => true
。单击它会再次加载列表,但会显示所选内容
处于编辑模式的行。可编辑行嵌入在form ... :remote => true
。
该行中的保存按钮是submit
button.
索引.html.haml
#editor
%table
- @items.each do |item|
%tr
= render :partial => 'row', :locals => { :item => item }
_row.html.haml
...
%td // a number of columns with attributes
...
%td
= link_to t("actions.edit"), edit_item_path(item), :remote => true
= link_to t("actions.delete"), item_path(item), :remote => true, :method => :delete, :data => { :confirm => "Are you sure?" }
编辑.html.haml
#editor
%table
- @items.each do |item|
%tr
- if item == @item
= form_for @item, :url => item_path(@item), :remote => true, do |f|
= render :partial => "row_form", :locals => { :f => f }
- else
= render :partial => 'row', :locals => { :item => item }
_row_form.html.haml
...
%td // a number of columns with editable attributes
...
%td
%button{ :type => "submit" }=t("actions.save")
= link_to t("actions.cancel"), items_path, :remote => true
Ajax 响应处理
$("#editor").on("ajax:success", function(event, data, status, xhr) {
$("#editor").html($(data).find("#editor").html());
});
Problem
当我在编辑模式下加载列表页面时/items/12/edit
,第 12 项的行是
可编辑。单击“保存”按钮可通过 Ajax 正确提交表单并加载
这/items
索引部分,用 jQuery 替换可编辑列表。点击
再次点击编辑按钮,再次加载编辑页面(例如/items/12/edit
), 和
嵌入的形式。只是这一次,表单不再提交
单击“保存”按钮。提交事件处理程序似乎没有附加到
动态加载远程表单。
Question
如何提交通过 Ajax 加载的远程表单(最好使用 Rails UJS 方法)?
重复项
我知道这个问题有重复,但没有一个得到回答。希望最终有人能给出明确的答案。
- 文档准备好后通过 Ajax 加载的 Rails 远程表单未提交
- 通过 ajax 加载的表单上的 :remote => true/data-remote