简体   繁体   English

防止在 jQuery 表单上提交

[英]Prevent submit on a jQuery form

I'm setting up a password control on a login form with jQuery and ajax.我正在使用 jQuery 和 ajax 在登录表单上设置密码控制。
So far, this is the script到目前为止,这是脚本

$(document).ready(function() {
    $("#login-form").submit(function(e) {
        var csrftoken = getCookie('csrftoken');
        var password = $('#login-password').val();
        var email = $('#login-email').val();

        $.ajax({
            url: "/password_check/",
            type: "POST",
            dataType: "json",
            data : {
                csrfmiddlewaretoken: csrftoken,
                password: password,
                email: email
            },
            success: function(result) {
                document.getElementById("login-error").innerHTML = result.response;
                event.preventDefault();
            }
        });
        return false;
    });
});

With this, the error gets caught when firing the submit button, but if the password is correct the submit doesn't work (even though the error doesn't show up anymore).这样,在触发提交按钮时会捕获错误,但如果密码正确,提交将不起作用(即使错误不再出现)。
What am I missing?我错过了什么?

You have an asynchronous ajax call, so by the time your success function fires, the form submit event has passed so you need to submit the form again but use the DOM method, which will bypass the jQuery event handler and allow the form to submit.您有一个异步 ajax 调用,所以当您的success函数触发时,表单提交事件已经通过,因此您需要再次提交表单,但使用 DOM 方法,这将绕过 jQuery 事件处理程序并允许表单提交。

success: function(result) {
    if(result == "correct"){
        document.getElementById("login-form").submit();
    } else {
        document.getElementById("login-error").innerHTML = result.response;
    }
}

As you didnt say what response indicates a correct password, I have used result == "correct" , so change that accordingly.由于您没有说明什么响应表示正确的密码,我使用了result == "correct" ,因此请相应地更改。

You have to return false only if u dont want to submit the form.仅当您不想提交表单时才必须返回 false。 If password is correct you need to return true in your case.如果密码正确,您需要在您的情况下返回 true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM