如何阻止远程表单提交? [英] How do I stop a remote form from submitting?

查看:118
本文介绍了如何阻止远程表单提交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个既可以远程使用又可以正常使用的表格.

I have a form that can be used both remotely and normally.

= form_for @comment, html: { class: 'comment-form' }, remote: request.xhr? do |f|
  = f.text_area :body
  = f.submit

我希望仅在body文本区域包含内容的情况下提交表单:

I want the form to submit only if the body textarea has content:

  $(document).on 'submit', '.comment-form', (e) ->
    text = $(this).find('#comment_body').val()
    false if text.length < 1

该代码在表单不是Ajax时有效.但是,当它处于远程状态时,它会失败,并且表单仍会提交.为什么?我也尝试过:

That code works when the form is not Ajax. But when it's remote, it fails and the form still submits. Why? I also tried:

if text.length < 1
  e.preventDefault()
  false

我正在将Rails 4与Turbolinks一起使用.

I'm using Rails 4 with Turbolinks.

更新:我尝试绑定ajax:beforeSend事件,它仍然提交:

Update: I tried binding the ajax:beforeSend event, it still submits:

  $(document).on 'page:load', '.comment-form', ->
    $(this).bind 'ajax:beforeSend', ->
      alert "hi"

我看不到任何警报...

I see no alert...

推荐答案

您可以为ajax:beforeSend事件实现一个处理程序,以防止提交您的表单.如果事件处理程序返回false,看来提交停止.

You could potentially implement a handler for the ajax:beforeSend event to prevent your form from being submitted. It looks like the submit stops if your event handler returns false.

Wiki: https://github.com/rails/jquery-ujs/wiki/ajax

示例实现:在beforeSend上停止$ .ajax

这篇关于如何阻止远程表单提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆