繁体   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