嗨,大家好,請幫助我解決我的問題。其實我試圖驗證我的電子郵件領域的形式使用javascript和張貼ajax請求來檢查該電子郵件是否存在,但我的JavaScript函數不會等到ajax響應和每次它返回false。我想返回true,當電子郵件不存在...我想驗證我的電子郵件字段在表格
$(document).ready(function(){
//global vars
var form = $("#signupForm");
var email = $("#email");
var email_error = $("#invalid");
//On blur
// userEmail.blur(validateEmail);
//On Submitting
form.submit(function(){
if(validateEmail()){
alert("submit true");
return true;
}else{
alert("submit false");
return false;
}
});
function validateEmail(){
//if it's NOT valid
alert("In email");
var a = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-][email protected][a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if(email.val() == ""){
email_error.html("Please enter your email ");
return false;
}
//if it's valid email
else if(filter.test(a)==false){
email_error.html("Please enter Valid email address");
return false;
}
else if(filter.test(a)==true){alert("elseif");
var baseUrl = '<?= base_url() ?>';
$.ajax({
type: "POST",
url: baseUrl+"index.php/index/validateUserEmail",
data: "useremail="+$("#email").val(),
success: function(msg){
alert(msg);
if(msg == "1")
{
$("#tick_cross").fadeIn("slow").html('<img src="'+baseUrl+'images/cross.png" />');
$("#emailValidate").val("1");
email_error.html("This email-Id already exists!");
return false;
}
else
{
$("#tick_cross").fadeIn("slow").html('<img src="'+baseUrl+'images/tick.png" />');
$("#emailValidate").val("0");
email_error.html(" ");
alert("alok");
return true;
}
}
});
}
else{
email_error.html(" ");
return true;
}
}
});
它不會像,因爲AJAX異步的工作性質,你需要使用一個回調來解決它 – 2013-03-20 11:48:14
嘗試設置選項異步:假在這裏: HTTP:// stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re – 2013-03-20 11:49:05
僅供參考,'async'在'v1.8'後不推薦使用 – asprin 2013-03-20 11:53:03