簡體   English   中英

AJAX郵寄表格無效。 它絕對無能為力

[英]AJAX post form won't work. It does absolutely nothing

我的代碼中有一個錯誤,頁面中還包含一個js文件,該文件阻止了$(document).ready(function(){

我正在嘗試匯總此登錄表單:

<form class="form" id="AjaxForm">
        <input type="text" name="username" placeholder="Username">
        <input type="password" name="password" placeholder="Password">
        <button type="submit" id="login-button">Login</button>
</form>

通過帶有此代碼的ajax:

var request;
$("#AjaxForm").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");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "login.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!");
    });

    // 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 occurred: "+
            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();
  });

我在這里找到的內容: PHP的jQuery Ajax POST示例

我正在嘗試將其發布到login.php,它檢查它是否是有效的用戶名和密碼。 但是,當我按下“登錄”按鈕時,它只是將用戶名和密碼放在url中,卻什么也不做。 當我添加action =“ login.php” method =“ POST”時,它提交表單但不通過ajax提交,因為當我注釋掉ajax代碼時,它仍然提交。 我正在努力防止這種情況。 對我的問題有任何見解嗎?

編輯:現在住在這里:http: //5f6738d9.ngrok.io/test/public/index.html用戶名和密碼已測試

您的提交按鈕是標准的提交類型按鈕,這意味着您的表單將正常提交。 根據您的HTML代碼,它將僅將表單提交到相同的URL。 JS代碼將沒有時間執行。 您需要做的就是通過添加取消默認的HTML表單提交

event.preventDefault();

您需要在提交偵聽器中添加第一件事。 因此,您的JS代碼將像這樣開始

$("#AjaxForm").submit(function(event){
    event.preventDefault();
    // Abort any pending request
    if (request) {
        request.abort();
    }
    //....

嘗試使用以下代碼:

$(document).ready(function(){
    $('#AjaxForm').on('submit', function(event){
        event.preventDefault();

        if(request){
            request.abort();
            request = false;
        }

        var $form = $(this);
        var serializedData = $form.serialize();
        var $inputs = $form.find("input, select, button, textarea");
        $inputs.prop("disabled", true);

        var request = $.ajax({
            url: 'login.php',
            type: 'POST',
            data: serializedData,
            success: function (data, textStatus, jqXHR) {
                // login was successful so maybe refresh the page
                window.location.reload();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // display form errors received from server
            },
            complete: function (jqXHR, textStatus) {
                request = false;
            }
        });
    });
});

檢查事件是否綁定在$(document).on('ready' ...否則事件將不會觸發,並且表單將僅通過AJAX正常提交或不提交。

您的代碼應如下所示:

$(document).on('ready', function () {
    var request;
    $("#AjaxForm").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");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "login.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!");
    });

    // 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 occurred: "+
            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();
  });
});

請注意,實際上從jQuery 1.8開始不推薦使用這些回調事件。

在所有情況下,您還需要確保在表單上設置了POSTaction屬性。

我個人將使用它代替:

$(document).ready(function(){
    $("#AjaxForm").on("submit",function(e){
        e.preventDefault();

        var $form = $(this);
        var $cacheData = $form.find("input, submit");
        var serializedData = $form.serialize();

        $.ajax({
            url: $form.attr("action"),
            type: $form.attr("method"),
            data: serializedData,
            xhrFields: {
                onprogress: function(e){
                    $cacheData.prop("disabled", true);
                    console.log(e.loaded / e.total*100 + "%");
                }
            },
            done: function(text){
                if(text == "Succes!"){
                    alert(text);
                } else {
                    alert(text);
                }
            },
            fail: function(xhr, textStatus, errorThrown){
                alert(textStatus + " | " + errorThrown);
            },
            always: function(){
                $cacheData.prop("disabled", false);
            }
        });
    });
});

這使您可以做一些有用的事情:

  1. 您可以在控制台中監控進度
  2. 僅僅因為Ajax成功了,並不意味着您就不會返回錯誤。 例如:錯誤的密碼。 因此,現在您可以簡單地回顯錯誤,此腳本將顯示它們。 回聲“成功!” 登錄正常時。

請記住,盡管此腳本要求您在表單中設置HTML屬性actionmethod

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM