返回False在jQuery.ajax中不起作用

Gil*_*ino 9 ajax jquery

我有一个用于更新用户信息的webform,当他更新他的电子邮件时,会通过以下方式执行验证,ajax()以便在新电子邮件地址已被其他用户使用时向他发出警告.

我正在尝试在电子邮件正在使用时取消表单提交,但return false;不起作用.

return false;if语句中的任何其他语句都正常工作,问题只出在jQuery.ajax()调用中.

这是实际的代码:

var email = jQuery('#email').val();
jQuery.ajax({
    type : 'GET',
    url : '/ajax/verify-email.php?email=' + email,
    success : function( d ) {
        if( d == '1' ) {
            alert('Another user is using this email');
            jQuery('input[name="email"]').focus();
            return false; // this guy over here is not working!!!!
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

有没有人有办法解决吗?

Dar*_*rov 22

AJAX中的A实际上非常重要.它代表异步.这意味着您触发了对服务器的请求,这可能需要一些时间来处理,之后您会收到响应.此响应发生在成功回调中.但由于这种情况比实际表单提交要晚得多,因此在回复之前,您的表单实际上已经提交.因此,从AJAX成功回调中返回false是没有任何意义的.你想要做的是从表单的提交处理程序返回false.让我们看看我们如何实现这一点.

您可以订阅.submit表单的处理程序并发送AJAX请求以验证电子邮件是否已被采用,如果未采用手动触发在成功AJAX回调中提交表单:

$('form').submit(function() {
    // we send an AJAX request to validate the unicity of the email
    $.ajax({
        url: '/ajax/verify-email.php',
        type: 'POST',
        data: { email: $('#email').val() },
        // we set the context to the form so that inside
        // the success callback 'this' points to the form
        context: this,
        success: function(result) {
            if (result != '1') {
                // If the server send something different than 1
                // we know that the email is unique and trigger
                // the submission of the form using the underlying
                // DOM element to avoid calling the .submit handler
                // recusrively
                this.submit();
            } else {
                // The email is not unique => we are informing
                // the user that the email is already in use
                alert('Another user is using this email');
                $('#email').focus();
            } 
        }
    });

    // we cancel the normal submission of the form    
    return false;
});
Run Code Online (Sandbox Code Playgroud)

也绝不依赖客户端验证.email is unique表单成功提交到服务器后,请确保您正在执行检查.如果您使用的是通过电子邮件字段中的唯一约束轻松实现的SQL数据库.