我正在使用 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;
}
请帮助纠正我的代码,以便仅当电子邮件实际存在时才对存在的电子邮件发出警报。
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 = "";
}
});
}
评论可能是正确的,但我感觉无论如何还有另一个问题:非空字符串在javascript中总是计算为true,并且由于服务器的响应没有输入(如果我没有记错的话),它总是会评估
true
是字符串“true”还是“false”...您应该测试字符串值或为 false
返回空字符串。
cfr 这个小提琴
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Email Registration Form</title>
</head>
<body>
<form id="registrationForm">
<label for="email">Email:</label>
<input type="email" id="email" required>
<button type="button" onclick="checkEmail()">Submit</button>
</form>
<script>
// Check if the email already exists in local storage
function isEmailExists(email) {
let storedEmails = JSON.parse(localStorage.getItem('registeredEmails')) || [];
return storedEmails.includes(email);
}
// Save the email to local storage
function saveEmail(email) {
let storedEmails = JSON.parse(localStorage.getItem('registeredEmails')) || [];
storedEmails.push(email);
localStorage.setItem('registeredEmails', JSON.stringify(storedEmails));
}
// Validate the email and take appropriate action
function checkEmail() {
let emailInput = document.getElementById('email');
let email = emailInput.value;
if (isEmailExists(email)) {
alert('Email already registered!');
} else {
saveEmail(email);
alert('Email registered successfully!');
// You can add additional actions here, such as submitting the form or redirecting to another page.
}
}
</script>
</body>
</html>