在 Rails 3 应用程序中,我想让浏览器在切换某个复选框时调用远程函数。 很容易做到这一点
:onclick => remote_function(...)
在 Rails 2 中,通过传递给复选框助手 。在 Rails 3 中,remote_* 函数已被弃用,因此我尝试了以下解决方法:
- 使用
form_tag ... :remote => 在复选框周围创建一个表单。 true
onclick
处理程序中调用 $("dummy_form").submit();
来提交表单
通过在与 Rails 捆绑在一起的rails.js 文件中的 是一个监听 submit
事件的观察者。然而,这些似乎只有在用户单击提交按钮时才会触发,而在调用 form.submit()
时不会触发(到目前为止仅在 FF 中进行了测试)。
这会产生不良影响,即提交不是通过 AJAX 在后台完成,而是以正常方式完成,因此浏览器离开当前站点并显示来自控制器的响应。
有人知道解决方法吗?也许有一种完全不同的方式来获得相同的功能?
In a Rails 3 app, I want to make the browser call a remote function whenever a certain checkbox is toggled. In Rails 2, this was easy to do by passing
:onclick => remote_function(...)
to the checkbox helper. In Rails 3, the remote_* functions are deprecated, so I tried the following workaround:
- create a form around the checkbox using
form_tag ... :remote => true
- submit the form by calling
$("dummy_form").submit();
from the onclick
handler
In the rails.js file that comes bundled with Rails is an observer that listens for submit
events. However, these only seem to be triggered when the user clicks on a submit button, but not when form.submit()
is called (so far tested only in FF).
This has the unwanted effect that the submit is then not done in the background via AJAX, but the normal way, so the browser leaves the current site and displays the response from the controller.
Does anyone know a workaround? Maybe a completely different way to get the same functionality?
发布评论
评论(1)
您可以通过调用来提交表单:
这将使用 AJAX 将表单提交到给定 form_tag 的 url 并评估收到的响应,因此它必须使用 JS 响应。如果您不希望这样做,请更改 onSuccess 实现。
如果表单提交是一种解决方法,正如您所说,那么您也可以手动处理复选框上的单击事件并发送 AJAX 请求:
You can submit the form by calling:
This will submit the form using AJAX to the url given to form_tag and evaluate received response, so it has to respond with JS. Change the onSuccess implementation if you don't want that.
If the form submission is a workaround, as you say, then instead of submitting the whole form you could also handle the on-click event on the check-box manually and send an AJAX request: