AJAX帖子表格不起作用。它什么都没做

时间:2015-07-05 15:42:57

标签: javascript php jquery ajax forms

我的代码中有一个错误,我的页面中还包含一个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();
  });

我在这里找到了:jQuery Ajax POST example with PHP

我试图将其发布到login.php,检查它是否是有效的用户名和密码。但是当我按下“登录”按钮时,它只是将用户名和密码放在网址中,什么都不做。当我添加 action =&#34; login.php&#34; method =&#34; POST&#34; 它提交表单但不通过ajax,因为当我评论ajax代码时,它仍然提交。我试图阻止这一点。关于我的问题的任何见解?

编辑:现在住在这里:http://5f6738d9.ngrok.io/test/public/index.html用户名和密码是test

3 个答案:

答案 0 :(得分:0)

您的提交按钮是标准提交类型按钮,表示您的表单将正常提交。根据您的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;
            }
        });
    });
});

答案 1 :(得分:0)

检查事件是否绑定在$(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属性。

答案 2 :(得分:0)

就个人而言,我会改用它:

$(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是成功的,并不意味着您无法返回错误。例如:密码错误。所以现在你可以简单地回复错误,这个脚本将显示它们。 Echo&#34; Succes!&#34;登录时很好。
  3. 请注意,此脚本要求您在表单中设置HTML属性actionmethod

相关问题