我正在尝试向 ResetPassword 函数添加验证。验证工作正常,但我遇到了另一个问题,在添加验证后,我的 ResetPassword 函数无法工作。任何人都可以指导我正确的方向吗?谢谢。
HTML 代码:
<div class="PopUpBG">
<div class="PopUp">
<h3 class="modal-title">
<span>Reset PAssword</span>
</h3>
<form id="form">
<input type="email" name="ResetEmail" id="ResetEmail" placeholder="Email Adresse" required/>
<input type="submit" class="btn btn-success" value="Send" onclick="ResetPassword(this)"/>
</form>
</div>
</div>
重置密码和验证码:
function ResetPassword(e) {
var email = $("#ResetEmail").val();
if ($("#form").validate()) {
return true;
} else {
return false;
}
$(".PopUp").html("We have sent mail to you");
$.ajax(
{
type: "POST",
url: "/Account/loginRequestResetPassword",
dataType: "json",
data: {
Email: email,
},
complete: function () {
console.log("send");
$(".PopUpBG").fadeOut();
}
})
}
最佳答案
问题是因为您在发送 AJAX 请求之前总是退出该函数,因为您使用了 return
if
的两个条件中的声明陈述。
更改逻辑,仅在验证失败时退出该函数:
function ResetPassword(e) {
if (!$("#form").validate())
return false;
$.ajax({
type: "POST",
url: "/Account/loginRequestResetPassword",
dataType: "json",
data: {
Email: $("#ResetEmail").val().trim(),
},
success: function() {
console.log("send");
$(".PopUp").html("We have sent mail to you");
setTimeout(function() {
$(".PopUpBG").fadeOut();
}, 10000); // fadeout the message after a few seconds
},
error: function() {
console.log('something went wrong - debug it!');
}
})
}
另请注意,我修改了逻辑,仅在请求完成后显示成功的电子邮件消息。您当前的代码可以向用户显示“电子邮件已发送”消息,即使该功能仍有可能失败。
关于javascript - jQuery 验证 AJAX 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47513754/