0

我首先想为数据库中的插入发布一些 ajax 数据,这工作正常,但提交标准 html 表单失败: $("#foo").submit(); 控制台消息无限循环:-/

<script type="text/javascript"> 
// variable to hold request var request; 
// bind to the submit event of our form $("#foo").submit(function(event){
    // abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);
    // let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea, text, hidden");
    // serialize the data in the form
    var serializedData = $form.serialize();

    // let's disable the inputs for the duration of the ajax request
    $inputs.prop("disabled", true);

    // fire off the request to /form.php
    request = $.ajax({
        url: "/insert_payment_data.php",
        type: "post",
        data: serializedData
    });

    // callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // log a message to the console         
    console.log("Hooray, it worked!");
    $("#foo").submit();
});

    // callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // log the error to the console
        console.error(
            "The following error occured: "+
            textStatus, errorThrown
        );
    });

    // callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // reenable the inputs
        $inputs.prop("disabled", false);
    });

    // prevent default posting of form
    event.preventDefault(); });

</script>

这让我发疯了:-(

4

1 回答 1

1

这是正常的 :

$("#foo").submit();

您方法末尾的这一行request.done正在触发表单的提交,这可能会触发 AJAX 请求,这会request.done无限地触发 ... 等等:-)

我要做的(尝试)是删除该行,并删除event.preventDefault();您在底部的语句,以便在您完成 AJAX 请求后您的提交将像往常一样运行。

于 2013-07-03T10:16:08.150 回答