【发布时间】:2016-01-13 11:38:33
【问题描述】:
由于某种原因,我无法抛出错误消息来说明我的用户表中是否存在电子邮件。我知道因为 AJAX 是异步的,所以我不能在完整函数中使用 try 和 catch 错误消息。但是我试过把它拆分成函数,还是不行。
Try, Catch Function(我确实在我的代码中的其他地方调用它)
try {
// Check fields are not empty
if (!firstName || !lastName || !aquinasEmail || !sPassword || !sCPassword || !Gender) {
throw "One or more field(s) have been left empty.";
}
// Check the email format is '@aquinas.ac.uk'
if(!emailCheck.test(aquinasEmail)) {
throw "The email address you entered has an incorrect email prefix. ";
}
// Check there are not any numbers in the First or Last name
if (!regx.test(firstName) || !regx.test(lastName)) {
throw "First Name or Last Name is invalid.";
}
// Check the confirmation password is the same as the first password
if (sPassword != sCPassword) {
throw "The two passwords you've entered are different.";
}
if(duplicatedEmail()) {
throw "Sadly, your desired email is taken. If you have forgotten your password please, <a href=\"#\">Click Here</a>";
}
} catch(err) {
if (!error) {
$('body').prepend("<div class=\"error alert\">"+err+"</div>");
$('.signupInput.sPassword').val('');
$('.signupInput.sCPassword').val('');
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {$('.error.alert').remove();});
}, 2600);
}
event.preventDefault();
}
AJAX 功能:
function duplicatedEmail() {
// Use AJAX function to do verification checks which can not be done via jQuery.
$.ajax({
type: "POST",
url: "/login/ajaxfunc/verifyReg.php",
dataType: "JSON",
async: false,
data: $('.signupForm').serialize(),
success: function(data) {
if (data.emailTaken == true) {
return true;
} else {
return false;
}
}
});
}
verifyReg.php
<?php
header('Content-Type: application/json', true);
$error = array();
require_once '../global.php';
$_POST['aquinas-email'] = "aq142647@aquinas.ac.uk";
// Check if an email already exists.
$checkEmails = $db->query("SELECT * FROM users WHERE aquinasEmail = '{$_POST['aquinas-email']}'");
if ($db->num($checkEmails) > 0) {
$error['emailTaken'] = true;
} else {
$error['emailTaken'] = false;
}
echo json_encode($error);
?>
【问题讨论】:
-
你到底想达到什么目的?你想在 AJAX 调用出错时抛出异常?
-
我想检查输入的电子邮件是否存在。
-
看看这个answer它可以帮助你:
-
同步请求是一种不好的做法。
标签: javascript jquery ajax try-catch