Javascript 阻止基于 ajax 响应的提交

Javascript preventing submit based on ajax response

本文关键字:响应 提交 ajax Javascript      更新时间:2023-09-26

我不明白为什么这段代码不会阻止提交。所有 html 都正确链接。所有警报都按预期显示。 我似乎并没有失去对事件的范围。任何建议,修复或解释都会很棒!

//Alert the potential customer if the email entered already exists.
function emailUniqueness() {
// When the Submit Button is clicked, then execute the following function... 
 $('#form').submit(function(event) {                 
    //Remove error messages if they exist
    $("#emailNotUniqueErr").empty();
    $("#emailNotUniqueErr").removeClass('alert alert-warning');
    //Make the call to servlet method
    $.ajax({
        url: 'http://localhost:8080/ShoppingCart/ajax.do',
        success: function(response) {
            searchForEmail(response, event);
        }
    });
    //event.preventDefault(); works when placed here but is pointless.   
});
}
function searchForEmail(response, event) {
    //alert returns type "submit"
    alert(event.type);
    var emailEntry = $("#email").val();
    var emailExists = false;
    $.each(response, function(index, item) { 
        if(emailEntry == item.email) {
            //Set to true when a match is found
            emailExists = true;
            //Exit the .each loop
            return false;
        }
    });
//alert returns appropriate true or false for input entry
    alert(emailExists);
    if(emailExists) {
        //still is type submit
        alert(event.type);
        //Properly print the warning if email exists
        $("#emailNotUniqueErr").addClass('alert alert-warning col-sm-offset-2');
        $('<a href="#" class="close" data-dismiss="alert">&times;</a>').appendTo("#emailNotUniqueErr");
        $('<strong>Warning! Account already exists. One account per Email.</strong>').appendTo("#emailNotUniqueErr");
        //does not prevent submit???
        event.preventDefault();

    } else {
        //No match found allow submit, remove errors
        $("#emailNotUniqueErr").empty();
        $("#emailNotUniqueErr").removeClass('alert alert-warning');
        return true;
    }
}

ajax调用是异步的。因此,行searchForEmail(response, event);的执行会有一些延迟(当请求响应时)。执行时,表单已提交。执行顺序如下。

  1. 调用函数 emailUniqueness()并开始执行函数
  2. 发送ajax请求,计划在响应到来后执行回调
  3. 函数emailUniqueness()函数执行结束
  4. 表单提交
  5. ajax请求的响应来了,执行了回调,searchForEmail(response, event);被调用
  6. event.preventDefault() 被调用(在提交表单后调用)

您必须在函数中调用event.preventDefault(); emailUniqueness()该方法,这会将顺序更改为以下内容。

  1. 调用函数emailUniqueness()并开始执行函数
  2. 发送ajax请求,计划在响应到来后执行回调
  3. 调用event.preventDefault()(这会阻止表单提交)
  4. 函数emailUniqueness()执行结束
  5. ajax请求的响应来了,执行了回调,searchForEmail(response, event)被调用

作为解决方案,

  1. 阻止在函数emailUniqueness内提交表单
  2. 提交带有$('#form').submit()的表单searchForEmail函数。