我正在检查,如果电子邮件存在或不使用javascript,但它正在解雇"电子邮件已经存在"每次即使电子邮件尚不存在。代码如下:
Javascript代码:
function chkemailExist(source, args) {
var exists;
$.ajax({
type: "POST",
url: "Register.aspx/DoesUserExist",
data: "{'emailid': '" + args.Value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (result) {
exists = result.d;
}
});
args.IsValid = exists;
if (!exists) {
var message="Email already exist for" + args.Value + ". ";
alert(message);
}
else { document.getElementById('ContentPlaceHolder1_CustomValidator1').innerHTML = ""; }
}
网络方法:
[WebMethod]
public static bool DoesUserExist(string emailid)
{
Boolean flg = true;
//Int32 cntchk = 0;
PAL_Register reg = new PAL_Register();
BAL_Register bal_reg = new BAL_Register();
reg.UserName = emailid;
flg = bal_reg.checkusername(reg);
return flg;
}
请帮助我更正我的代码,以便只有在实际存在电子邮件时才会发出现有电子邮件的警报。
答案 0 :(得分:2)
AJAX 异步 - 您正在尝试对尚未存在的变量执行逻辑,因为调用正在进行中。在回调中做你的工作!
function chkemailExist(source, args) {
var exists;
$.ajax({
type: "POST",
url: "Register.aspx/DoesUserExist",
data: "{'emailid': '" + args.Value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (result) {
exists = result.d;
args.IsValid = exists;
if (!exists) {
var message="Although you indicated you're a new customer, an account already exists for " + args.Value + ". ";
alert(message);
}
else {
document.getElementById('ContentPlaceHolder1_CustomValidator1').innerHTML = "";
}
});
}
答案 1 :(得分:0)
评论可能是真的,但我觉得还有另一个问题:非空字符串总是在javascript中评估为true,并且由于服务器的响应没有输入(如果我没有记错),它将永远评估为true
字符串为“true”或“false”...您应该测试字符串值或为false
返回一个空字符串。
cfr this fiddle