我有这个部分工作的代码。它假设要检查数据库中的现有电子邮件地址。如果没有电子邮件,则return true;
$(document).ready(function() {
var email_check = 0;
var checking_html = '<img src="http://i.imgur.com/Y8wXAZp.gif" /> Checking...';
var characters_error = 'Minimum amount of chars is 6';
//when button is clicked
$('.register').click(function(){
//run the character number check
if($('#email').val().length < 1){
$('#email_result').html(characters_error);
return false;
}
else{
//else show the cheking_text and run the function to check
$('#email_result').html(checking_html);
alert(check_email_availability());
}
});
});
//function to check email availability
function check_email_availability(){
//get the email
var email = $('#email').val();
//use ajax to run the check
$.post("check_email.php", { email: email },
function(result){
email_check = 0;
//if the result is 1
if(result == 1){
//show that the email is available
email_check = 1;
}else{
email_check = 0;
}
});
if (email_check == 1){
return true;
}else{
return false;
}
}
现在,问题是如果当前状态为false
,当我输入数据库中没有的电子邮件并单击按钮时,我仍然会收到false
警报,并且当下次我点击按钮我得到true
警报。由于某种原因,该函数首先执行底部代码(检查email_check
值),然后执行该函数。这是为什么?我的代码出了什么问题?如何使其执行功能,然后检查email_check
值1
是否为{{1}}?
答案 0 :(得分:2)
我会改变这一点,在你的检查功能上放一个ajax成功回调。
success: function (data, status, xhr ) {
myFunctionShowEmailSuccess();
},
error: function (xhr, status, error) {
myFunctionShowEmailFailure();
}
答案 1 :(得分:0)
尝试这样做。
//function to check email availability
function check_email_availability(){
//get the email
var email = $('#email').val();
//use ajax to run the check
$.post("check_email.php", { email: email },
function(result){
email_check = 0;
//if the result is 1
if(result == 1){
//show that the email is available
return true;
}else{
return false;
}
});
}