2013-04-30 105 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);  
    }); 
});