我有简单的注册表格。 Ajax和表单工作正常,但不能通过变量连接它们,我的意思是当ajax检查电子邮件在数据库寄存器中时应该由变量error
停止,但它不是。
代码:
$('.login').submit(function(e) {
e.preventDefault();
var error = 0;
var self = $(this);
var $name = self.find('[type=name]');
var $email = self.find('[type=email]');
var $pass = self.find('[type=password]');
//MY AJAX
var email = $email.val();
$.ajax({
url: 'http://localhost/FPD/nowe/inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
//THAT ERROR VARIABLE DOESNT WORK OUTSIDE AJAX FUNCTION
error++;
}
},
error: function(xhr, textStatus, error) // THOSE ROWS
{
alert(error);
}
});
if (error!=0)return;
//THAT STILL WORKS EVEN AJAX ERROR
self.find('[type=submit]').attr('disabled', 'disabled');
self.children().fadeOut(300,function(){ $(this).remove() })
$('<p class="login__title">sign in <br><span class="login-edition">welcome to A.Movie</span></p><p class="success">You have successfully<br> signed in!</p>').appendTo(self)
.hide().delay(300).fadeIn();
// var formInput = self.serialize();
// $.post(self.attr('action'),formInput, function(data){}); // end post
}); // end submit
答案 0 :(得分:0)
原因是ajax被称为异步。您必须在ajax调用中设置async: false
。所以你的代码将成为:
$.ajax({
url: 'http://localhost/FPD/nowe/inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
async : false, //<----
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
//THAT ERROR VARIABLE DOESNT WORK OUTSIDE AJAX FUNCTION
error++;
}
},
error: function(xhr, textStatus, error) // THOSE ROWS
{
alert(error);
}
});
这将确保在ajax调用之后不会执行任何操作,除非您收到回复。