Ajax submits the form, disables the default form submission and retains the input data verification

Set οnsubmit="return login()" of the form and let the login function return false. Note that false is lowercase. I am used to writing Python, so I wrote it as False before.

html code: 

<form method="POST" id="login_form" onsubmit="return login()">

            <div class="input">
                <input type="text" name="username" placeholder="用户名/邮箱" required id="id_username">
            </div>
            <div class="input">
                <input type="password" name="password" placeholder="密码" maxlength="100" required id="id_password">
            </div>

            <div class="sign_up">
                <input type="submit" name="commit" value="登录" id="sign_up_btn">
            </div>

</form>

js code: 

function login() {
    form = $("#login_form")
    $.ajax({
        type: "POST",
        url: window.location.href,//表单接收url
        data: form.serialize(),
        success: function (data) {
            alert('success')

        },
        error: function (data) {
            alert('error')
        }
    });
    //返回false表单的默认提交事件
    return false
}

 

Guess you like

Origin blog.csdn.net/u011519550/article/details/115439792