2012-01-10 143 views
1

我有一些采用文本输入的值并将其放入MySQL数据库的jQuery。但是,当jQuery运行时,页面刷新并且表单中的变量几乎作为GET变量出现在URL中。但是,没有一个变量是GET。理想情况下,我希望网页不要刷新。jQuery POST刷新页面

的jQuery:

$('.commentBox').keypress(function(e) { 

    if(e.which == 13) { 
     if ($.trim($(this).val()) == ""){ 
      $('#nocomment').modal('show'); 
     } 
     else { 
      var form = $(this).siblings('.commentForm'); 
      var commentbox = $(this).val(); 

      $.ajax({ 
       type: "POST", 
       url: "../comment", 
       data: form.serialize(), 
       success: function(){ 
        commentbox.val(''); 
        form.siblings('.commentContainer').append(response); 
       } 
      }); 
     } 
    } 

}); 

HTML(从PHP呼应):

<form class='commentForm'> 
    <input type='hidden' name='record_id' value='$answerid[$f]' /> 
    <input type='hidden' name='question_id' value='$q' />"; 
    <input type='text' class='commentBox' placeholder='...comment' name='comment' autocomplete='off' />"; 
</form> 

回答

2

你必须要么返回false或防止默认情况下,这将停止的形式从提交:

$('.commentBox').keypress(function(e) 
{ 
    if(e.which == 13) 
    { 
     e.preventDefault(); // <-- This will stop the form from submitting. 

     if ($.trim($(this).val()) == "") 
     { 
      $('#nocomment').modal('show'); 
     } 
     else 
     { 
      var form = $(this).closest('.commentForm'); 
      var commentbox = $(this).val(); 
      $.ajax({ 
       type: "POST", 
       url: "../comment", 
       data: form.serialize(), 
       success: function(){ 
        commentbox.val(''); 
        form.siblings('.commentContainer').append(response); 
       } 
      }); 
     } 
    } 
}); 
+1

请不要使用返回false做到这一点。它打破了事件冒泡和捕获,这可能会使其他JavaScript与您的元素进行交互变得困难。 – Nate 2012-01-10 03:36:30

+0

@joseph我应该在哪里放置?我尝试了按键功能后,它不会让我在文本框中输入任何内容。然后我将它移到'else {'后面,然后我可以输入,但是当我按下输入时,什么也没有发生 – kirby 2012-01-10 03:37:33

+0

@ user802370 - 我将代码添加到了我的答案中。 – 2012-01-10 03:38:45

0

您需要防止按下Enter键时发生的默认操作,即通过GET提交表单。

e.preventDefault();

$('.commentBox').keypress(function(e) { 

    if(e.which === 13) { 

     // Prevent the default only when it's the enter key 
     e.preventDefault(); 

     if ($.trim($(this).val()) === ''){ 
      $('#nocomment').modal('show'); 
     } 
     else { 
      var form = $(this).siblings('.commentForm'); 
      var commentbox = $(this).val(); 

      $.ajax({ 
       type: "POST", 
       url: "../comment", 
       data: form.serialize(), 
       success: function(){ 
        commentbox.val('' ; 
        form.siblings('.commentContainer').append(response); 
       } 
      }); 
     } 
    } 

}); 
+0

我应该在哪里放置此代码 – kirby 2012-01-10 03:37:55

+0

答案更新以显示插入代码的位置。 – Nate 2012-01-10 03:40:31

+0

请看我最近对约瑟夫答案的评论 – kirby 2012-01-10 03:43:59