【问题标题】:Cancel submit on a rails remote form_for取消在 Rails 远程 form_for 上提交
【发布时间】:2012-11-10 18:53:01
【问题描述】:

我有一个 form_for(:remote=>true) 工作,但我想在提交之前显示一个常规的 javascript 确认框。

有没有办法做到这一点? 理想情况下,某种 :before 或 :onsubmit 可以接受取消提交,例如:return confirm("Are you sure?"); 或者可能是 javascript 事件挂钩?

谢谢

【问题讨论】:

    标签: jquery ruby-on-rails-3 forms


    【解决方案1】:

    您可以使用the confirm option 轻松做到这一点:

    <%= for_form @my_thing, remote: true do |f| %>
      <%= f.text_field :my_value %>
      <%= f.submit 'Submit', confirm: 'Are you sure?' %>
    <% end %>
    

    您需要使用Rails UJS driver(在新的 Rails 项目中默认启用)才能无缝运行。

    如果你愿意,还有hooks into the form submission lifecycle you can access

    • ajax:beforeSend - 在发出 XHR 请求之前触发;返回 false 取消请求
    • ajax:success - 在服务器成功响应时触发
    • ajax:error - 在服务器的错误响应时触发
    • ajax:complete - 在服务器成功或错误响应时触发

    因此,作为示例,您应该能够使用如下代码来模仿 confirm 表单助手选项:

    $("#my_remote_form").on('ajax:beforeSend', function() {
      return confirm("Are you sure?");
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-05
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多