2011-12-31 84 views
1

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

的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> 
+2

将'return false;'加到你的提交函数中。 – Virendra 2011-12-31 19:32:08

+0

@Virendra我应该在哪里添加返回false?在preventDefault之后还是之前? – kirby 2011-12-31 19:33:16

+0

就在最后'});'。 – Virendra 2011-12-31 19:34:18

回答

3

我不认为你的selectoron方法是否正常工作。试试:$('form').on('submit', function(e) {你确定你已经用类answerContainer包装你的表单吗?

,然后公正,以确保不使用$.post使用$.ajax

this内的在我的元素如。不是第一个选择器.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(''); 
      } 
     }); 
    }); 
}); 
+0

里面,这是个解决方案,我不知道我的代码有哪些部分没有工作,但是这是一个很好的答案,非常感谢 – kirby 2011-12-31 19:50:48

+0

Im eater。一个错误:'var form = $(this).closest(“form”)。'应该是'var form = $(this)'。 – andlrc 2011-12-31 19:52:24

+0

@ user802370,即使您正在阻止默认表单操作,提交表单:$ .post($(form).attr('action'),'。正如答案中所述,使用'.ajax'而不是'.post'确实可以修复它。 – Sparky 2011-12-31 19:53:21

相关问题