【问题标题】:Form still submits on preventDefault表单仍然在 preventDefault 上提交
【发布时间】:2011-12-31 19:30:10
【问题描述】:

我正在使用 jQuery 将表单数据提交到表单操作中的文件。但是,当我提交表单时,浏览器会重定向到操作 (comment.php)。我不知道为什么这是因为e.preventDefault() 应该停止浏览器的重定向。理想情况下,我希望浏览器不重定向并保留在当前页面(index.php)上。

jQuery:

<script type='text/javascript'>
    $('document').ready(function(){
        $('.commentContainer').load('../writecomment.php');
        $('.answerContainer').on('submit', 'form', function(e){
            e.preventDefault();
            var form = $(this).closest('form');
            $.post($(form).attr('action'), 
            $(form).serialize(), 
            function() {
                $('.commentContainer').load('../writecomment.php');
                $('.commentBox').val('');
            }
        });
    });
</script>

HTML 表单:

<form method='POST' action='../comment.php'>
    //form contents
</form>

【问题讨论】:

  • return false; 添加到您的提交功能中。
  • @Virendra 我应该在哪里添加 return false?在 preventDefault 之后还是之前?
  • @Virendra 不走运。仍然重定向
  • 尝试将onsubmit="return false;" 添加到您的表单中。
  • @Virendra 页面没有重定向,但是现在数据没有放在数据库中

标签: forms jquery preventdefault


【解决方案1】:

我认为您的 selectoron 方法无法正常工作。试试看:$('form').on('submit', function(e) { 你确定你已经将你的表单包裹在一个类为answerContainer的元素中了吗??

然后确保不要使用$.post 使用$.ajax

this 在 i 元素内,例如。 form不是第一个选择器.answerContainer

$('document').ready(function(){

    $('.commentContainer').load('../writecomment.php');

    $('.answerContainer').on('submit', 'form', function(event) {
        event.preventDefault();
        var $form = $(this);
        $.ajax({
            "url": $form.attr("action"),
            "data": $form.serialize(),
            "type": $form.attr("method"),
            "response": function() {
                $('.commentContainer').load('../writecomment.php');
                $('.commentBox').val('');
            }
        });
    });
});

【讨论】:

  • 这就是解决方案。我不确定我的代码的哪一部分具体不起作用,但这是一个很好的答案。非常感谢
  • 我是食客。但是你至少有一个错误。 var form = $(this).closest("form"). 应该是 var form = $(this)
  • @user802370,即使您正在阻止默认表单操作,此行也会继续提交表单:$.post($(form).attr('action'),。如答案所述,使用.ajax 而不是.post 才是真正解决问题的方法。
  • @AndreasAL 这不是原始问题的一部分,但是当我使用您的代码时,commentBox 值并不清楚。当我使用我的代码时也不清楚,但是关于为什么会发生这种情况的任何猜测?我仔细检查了 textarea 有类 commentBox
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多