我的应用程序必须使用 Bootstrap 4.1 加载模式,其中包含在加载模式时动态生成的表单。
表单应该使用 AJAX 提交,但是即使设置了 remote: true 标志,它也会作为 HTML 提交。
我知道因为表单在页面加载时不存在,所以 Javascript 事件没有绑定到它。
表单是通过 AJAX 添加到页面的,所以当所有偶数绑定发生时它不存在。流程是:
- 用户点击“添加新的从属关系”并打开模态;
- 用户选择隶属类型;
- 根据选择的附属类型,通过 AJAX 生成一个表单并将其插入到已经打开的模式中。
- 当用户点击“保存”时,预计表单应该通过 AJAX 提交,模态消失并且新的隶属关系被添加到列表中
在这种情况下,如何在加载表单后将表单绑定到 JS 事件?或者远程提交的最佳方式是什么?
编辑
到目前为止,我发现,如果页面直接在主体中加载而不是使用 AJAX,它的工作原理和外观与在模式中时完全相同。
在模态中,我尝试使用以下几种方式从控制台运行提交:
$("#new_affiliation").trigger('submit'); 使用 HTTP 提交表单
nativeFormEl = $("#new_affiliation")[0]; Rails.fire(nativeFormEl, '提交'); 返回真,但什么也不做
nativeFormEl = $("#new_affiliation")[0]; Rails.handleRemote.call(nativeFormEl); 使用 AJAX 提交表单,但抛出异常:
TypeError: Cannot read property 'target' of undefined at Rails.stopEverything (application-785dee507ca17b63962581aa57866b38a001fd1a70d0bec06d994151a9cfc39a.js:160) at HTMLFormElement.Rails.handleRemote (application-785dee507ca17b63962581aa57866b38a001fd1a70d0bec06d994151a9cfc39a.js:629) at :1:20
在这一点上,我想知道,为什么 Rail.fire 返回 true,但什么也没做?
在主页上
<%= button_tag "New affiliation", type: :button, class: "btn btn-success", id: "new-affiliation-button" %>
加载模态:
$ ->
$("#new-button").on 'click', (evt) ->
url = 'some application path'
$.ajax url,
type: 'GET'
dataType: 'script'
data: {
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
$("#detail-modal").modal('show')
在控制器的操作成功时加载表单 (new.js.erb)
$("#detail-form").html("<%= j render(partial: 'form') %>");
表单标签
<%= simple_form_for([@source, @skater, skater_affiliation], remote: true, authenticity_token: true, id: "affiliation-data") do |f| %>
控制器中的创建动作
respond_to do |format|
if @source.valid?
format.html { redirect_to edit_source_path(@source) }
format.json { render "success" }
format.js { render "success" }
else
format.html { render "new" }
format.json { render "new" }
format.js { render "new" }
end
end
呈现的形式
<form class="simple_form new_affiliation" id="new_affiliation" novalidate="novalidate" enctype="multipart/form-data" action="/affiliations" accept-charset="UTF-8" data-remote="true" method="post">
[some fields...]
<div class="row top-spacer-20">
<div class="col-12"><input type="submit" name="commit" value="Save" class="btn btn-default btn btn-success" data-disable-with="Save"></div>
</div>
</form>