2013-04-30 101 views
0

我以前成功地使用了$.get,但無法使其在jQuery提交事件中工作。根據jQuery文檔,提交事件攔截表單的提交事件,並且只要您返回false,就會阻止HTML表單操作發生。我已經驗證了這個作品。在下面的代碼中,我使用了兩次$.get(一次在事件處理程序之前,然後在其中)。它在第一種情況下效果很好,但在提交事件中失敗。jQuery.get在jQuery提交事件中失敗

test.php的代碼:

<?php 
$handle = $_GET['handle']; 
echo($handle); 
?> 

client.php代碼:

<div> 
<form id="message_box_form" style="height:100px;width:300px" method="get" action="../phpDB/test.php"> 
    <textarea id="message_box" style="height:30px;width:250px;" type="text" name="messagecontent"></textarea> 
    <input id="share_button" name="share_button" type="submit" value="Share" />  
</form> 
</div> 

<script type="text/javascript"> 
jQuery(document).ready(function($) { 

    $.get("../phpDB/test.php",{handle:'nightstalker'}, function(data){    
     alert(data); // This works fine 
    }); 

    $('#message_box_form').submit(function() { 
     alert('jQuery submit handler called'); //This happens 
     $.get("../phpDB/test.php",{handle:'rodbender'}, function(data){ 
      alert(data); // This NEVER happens 
      return false; 
     }); 
    }); 
}); 
</script> 

回答

2

return false;是在錯誤的地方:

$('#message_box_form').submit(function() { 
    alert('jQuery submit handler called'); //This happens 
    $.get("../phpDB/test.php",{handle:'rodbender'}, function(data){ 
     alert(data);  
    }); 
    return false; // should in the callback of submit. 
}); 

或者你可以使用e.preventDefault();

$('#message_box_form').submit(function(e) { 
    e.preventDefault(); 
    alert('jQuery submit handler called'); //This happens 
    $.get("../phpDB/test.php",{handle:'rodbender'}, function(data){ 
     alert(data);  
    }); 
});