我正在验证表单,需要通过ajax查找电子邮件,以检查它是否已被使用。这一切都很好,除了它设置变量时,它没有通过函数的其余部分
使用$('#account_text_update').click(function(e){ // signup
errors = 0;
// email validation
email = $('#account_email').val();
if(email.length==0) errors = account_error('#account_email','Please enter an email address');
else {
regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(email.match(regex) == null) errors = account_error('#account_email','Please enter a valid email address');
else {
$.ajax({ // check if email already used
type : 'POST',
url : '//'+base_url+'/ajax/account-email.php',
data : 'email='+email,
success : function(data) {
if(data=='yes') errors = account_error('#account_email','Email already exists');
}
});
}
}
if(errors==0) update();
});
因此变量为errors
,它最初设置为0,如果ajax电子邮件检查表明该电子邮件已被使用,则会设置errors
变量。但是,在更新时,即使出现错误,它仍会更新。
如何在整个函数的其余部分使ajax变量全局化?
答案 0 :(得分:1)
By default, AJAX request is asynchronous (non-blocking), which means that the "success" function is called when the ajax request has finished (it has received a response). The browser won't wait for them to be completed in order to continue its work.
If you want to reuse the ajax response later within your code, then you must use $.ajax({async:false})
, which will lock the browser and make a synchronous request.
答案 1 :(得分:0)
首先,您应尽量避免使用全局变量,可能会重写整个代码块。
针对您的具体问题,它与Promise的概念有关。最后一行:
if(errors==0) update();
将在您的ajax调用完成其成功回调之前执行。因此,errors
将始终为零,并且会立即调用update()
。
有几种方法可以解决这个问题 将此行移至成功回调:
success: function (data) {
if (data == 'yes')
errors = account_error('#account_email', 'Email already exists');
if(errors==0) update();
}
或者,在ajax
的末尾管道var validateAjax = $.ajax(...)
//...
validateAjax..always(function(){ if(errors==0) update(); });