Ajax post工作一次,然后再次工作,但不是异步的


Ajax post works once then works again but not asynchronously

我想做的就是简单地将论坛异步发布到php页面,并返回它对特定id的响应。

当我第一次提交时,一切都如预期的那样工作。文本被发送到add .php,并立即返回新的项目列表,而无需刷新页面。

第二次提交文本时,它似乎忽略了ajax的东西。相反,它让我执行append.php并只显示列表。尽管它仍然提交表单并添加到数组中。这使我怀疑我的问题出在脚本中。

所以我的问题是,我需要做什么为我的表单连续使用AJAX工作不止一次?

index . php

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>For Testing Ajax</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script>
            $(document).ready(function(){
                // Bind to the submit event
                $(".ajax").submit(function(event){
                    // Get local variables
                    var form = $(this);
                    // Get inputs of this form
                    var inputs = form.find("input, select, button, textarea");
                    // Get the data to post
                    var serializedData = form.serialize();
                    // prevent additional requests during the duration of this one
                    inputs.prop("disabled", true);
                    // Make the request to the form's ACTION property
                    var request = $.ajax({
                        url: form.prop("action"),
                        type: "post",
                        data: serializedData
                    }).done(function (response, textStatus, jqXHR){
                        // Success
                        console.log("Hooray, it worked!");
                        // Return response to the ID according to the form's NAME property
                        $("#"+form.prop("name")).html(response);
                    }).fail(function (jqXHR, textStatus, errorThrown){
                        // Failure
                        console.error(
                            "The following error occured: "+
                            textStatus, errorThrown
                        );
                    }).always(function () {
                        inputs.prop("disabled", false);
                        form.unbind('submit');
                    });
                    event.preventDefault();
                    return false;
                });
            });
        </script>
    </head>
    <body>
        <h1>You're on the main page.</h1>
        <div id="list">
            <form class="ajax" method="POST" name="list" action="append.php">
                <input type="text" name="text">
                <input type="submit" value="Append">
            </form>
            <?
            $list = json_decode(file_get_contents('list.json'),true);
            echo '<ul>';
            foreach($list as $item){
                echo '<li>'.$item.'</li>';
            }
            echo '</ul>';
            ?>
        </div>
    </body>
</html>

append.php

<?
// Get the POST stuff
$text = $_POST['text'];
Check if anything was indeed submitted
if (isset($_POST['text'])) {
    // Get current array
    $list = json_decode(file_get_contents('list.json'),true);
    // Add to the array
    $list[] = $text;
    // Save changes to the file
    file_put_contents('list.json',json_encode($list));
    // Return the forum and the array in an unorganized list
    echo '
        <form class="ajax" method="POST" name="list" action="append.php">
            <input type="text" name="text">
            <input type="submit" value="Append">
        </form>
        <ul>';
    foreach($list as $item){
        echo '<li>'.$item.'</li>';
    }
    echo '</ul>';
}
?>
感谢您的宝贵时间!

PS:我使用jQuery v2.0.2

问题是form.unbind('submit');,它是解除绑定的事件处理程序,所以它不会执行下一次。

让我们看看,在div

中有一个表单
<div id="list">
    <form class="ajax" method="POST" name="list" action="append.php">

,在成功回调中你做

$("#"+form.prop("name")).html(response);

作为表单的名称是list,你有效地替换了DIV内的一切与id #list与ajax调用返回的任何,你最初绑定事件处理程序的元素消失了!

要解决这个问题,使用一个委托的事件处理程序,它也可以与你放在那里的新表单一起工作

$(document).on("submit", ".ajax", function(event){
     // your code here
});

您还在always处理程序中解除绑定事件,但这并不重要,因为ajax调用成功后表单不再存在。