jQuery.get在jQuery提交事件中失败

时间:2013-04-30 01:10:46

标签: javascript jquery ajax

我过去曾成功使用$.get,但无法在jQuery提交事件中使用它。根据jQuery文档,submit事件拦截表单的提交事件,并且只要您返回false,就会阻止HTML表单操作发生。我已经验证了这项工作。在下面的代码中,我使用$.get两次(在事件处理程序之前一次,然后在其中)。它在第一种情况下运行良好,但在提交事件中失败。

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>

1 个答案:

答案 0 :(得分: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);    
    });
});