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

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>

最佳答案

您的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);
    });
});

关于javascript - jQuery.get内部jQuery.get失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16290676/

10-17 00:02