"loadingFunction(this)", :complete => "complet-6ren">
gpt4 book ai didi

javascript - 如何在 form_remote_tag 的 :complete callback? 中获取表单标签的 JS DOM/JQuery 对象

转载 作者:行者123 更新时间:2023-11-30 06:46:03 25 4
gpt4 key购买 nike

在 Rails 2.3.3 中,我想做类似的事情:

<% form_remote_tag :url => "/some/path/", :loading => "loadingFunction(this)", :complete => "completeFunction(this,request)" do %>

基本上,我希望能够将该特定的表单标签传递给 :complete 或 :loading 回调函数(以相对方式 - 我不想使用 ID - 我希望能够获取标签:complete 调用对应于 :complete 调用针对表单标记**的自然结果。

参见 Rails documentation for form_remote_tag .特别是,Rails 为 onsubmit 事件生成如下代码:new Ajax.Request('/some/path/', {asynchronous:true, evalScripts:true, onComplete:function(request){completeFunction(this,request)} , onLoading:function(request){loadingFunction(this)}, parameters:Form.serialize(this)}); return false;"。注意函数调用是如何包装在 function(request){} 中的,它位于 new Ajax.Request() 中。

因此,“this”、“jQuery(this)”、“jQuery(this).closest('.someParentElementOfTheForm')”等都不起作用。


**我这样做是因为:我在加载页面时渲染任意数量的“form_remote_tag”,并且用户可以触发导致任意更多“form_remote_tag”出现的事件(每种形式具有相似的内容,但每个形式中的元素数量形式也是任意的)。如果我整个页面只有一个form_remote_tag,主要有几个问题:

  • 用户只会编辑页面的一个部分(在我当前的设计中对应一个表单),但是页面中所有表单元素的数据都必须在请求中发送

  • 这将需要某种困惑的方式来跟踪表单及其元素,为它们提供 ID,例如:“form-12”、“form-12-paramfield-13”等。

  • 这使得很难允许:用户提交一个表单,当该表单通过 AJAX 加载时,提交其他表单(包括触发导致新表单出现的事件的可能性,然后提交该表单),因为跟踪每个请求的响应数据的位置存在问题

最佳答案

您是否尝试过在 html 选项中传递以下回调

:html => { :loading => "#{remotefunction(options)}; return false;"} 或者:html => { :onloading => "#{remotefunction(options)}; 返回 false;"}

可以指定的回调是(按顺序):

:loading:   Called when the remote document is being loaded with data by the browser.
:loaded: Called when the browser has finished loading the remote document.
:interactive: Called when the user can interact with the remote document, even though it has not finished loading.
:success: Called when the XMLHttpRequest is completed, and the HTTP status code is in the 2XX range.
:failure: Called when the XMLHttpRequest is completed, and the HTTP status code is not in the 2XX range.
:complete: Called when the XMLHttpRequest is complete (fires after success/failure if they are present).

您可以通过为特定状态代码添加额外的回调来进一步优化 :success 和 :failure。

最近我实现了如下所示在我的远程表单中覆盖 onsubmit

 <% options = {:url => {:action =>"test", :id => 1}, :with =>"Form.serialize('test_form')" }%>
<% form_remote_tag :html=>{ :onsubmit =>"#{remote_function(options)}; return false" } do %>

关于javascript - 如何在 form_remote_tag 的 :complete callback? 中获取表单标签的 JS DOM/JQuery 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6768894/

25 4 0