繁体   English   中英

Rails中的远程模式形式,不触发AJAX事件

[英]Remote modal form in rails, not triggering AJAX events

我在Rails中创建了一个模式窗体,该窗体使用AJAX远程提交值。

出于某种原因,模态表单本身的提交不会触发任何AJAX事件。 如果我在页面中添加完全相同的表单代码(即不在模态上),则在提交时会触发AJAX事件。

这是我的代码:

//index.haml
= link_to 'New', new_foo_path, data: { remote: true, type: 'script'}

//_form.haml
= bootstrap_form_for @foo, remote: true do |f|  
  = f.text_field :bar
  = f.button "Save"


//foos_controller.rb
def create
  respond_to do |format|
    if @foo.save
      format.json { render json: @foo, status: :ok }
    else
      format.json { render json: @foo.errors, status: :unprocessable_entity }
    end
  end
end

//foo.coffee
$('#new_foo').on('ajax:success', (e, data, status, xhr) ->
  console.log 'Great success'
).on 'ajax:error', (e, data, status, xhr) ->
  console.log 'Great failure'

使用上面给出的代码,让我在提交具有未通过验证的值的表单时看到422错误。 此行为是预期的。 但是,这不会将上述消息打印到Chrome Dev Console日志中。 如果将表单代码添加到索引视图本身并从那里提交,则可以看到422错误以及在'foo.coffee'中分配的日志消息。

有人可以发现我所缺少的东西吗?

重新查看您的代码后,我确定了实际的问题可能是什么。 模态表单是使用JS加载的,这意味着当您的页面在浏览器中加载时不存在。 这就是为什么您没有/不能将回调代码绑定到表单的JS的原因,因为您要绑定/注册它的源Dom不存在。 要解决此问题,您需要将回调函数注册到页面中存在的元素,该元素在加载第一时间并且您的表单必须是其子元素之一时才存在。 这个概念称为事件委托 因此,以下代码将起作用:

$('body')
.on 'ajax:success', '#new_foo', (e, data, status, xhr) ->
  console.log 'Great success'
.on 'ajax:error', '#new_foo', (e, data, status, xhr) ->
  console.log 'Great failure'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM