我无法弄清楚为什么这段代码不会阻止提交。所有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">×</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;
}
}
答案 0 :(得分:0)
ajax
调用是异步的。因此,行searchForEmail(response, event);
执行时会有一些延迟(当请求响应时)。执行时,表单已经提交。执行顺序如下。
emailUniqueness()
并启动函数的执行ajax
请求以安排在响应到来之后执行的回调emailUniqueness()
函数执行结束ajax
请求的响应,执行回调,searchForEmail(response, event);
被称为event.preventDefault()
被调用(在提交表单后调用)您必须在event.preventDefault();
函数中调用方法emailUniqueness()
,该方法会将订单更改为以下内容。
emailUniqueness()
并启动函数的执行ajax
请求以安排在响应到来之后执行的回调event.preventDefault()
被调用(这会阻止表单提交)emailUniqueness()
函数执行结束ajax
请求的响应,执行回调,searchForEmail(response, event)
被称为作为解决方案,
emailUniqueness
函数$('#form').submit()
函数内提交searchForEmail
表单。