2011-12-31 93 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

相關問題