我读到了AJAX并从中获取了调用,我试图重构代码,以便开始工作。
处理接受回调的函数。
我创建了代码,但仍然可变的错误在AJAX之外无效。
$('.login').submit(function(e) {
e.preventDefault();
var error = 0;
var email = $email.val();
// function that makes a request and returns a promise:
function testAjax() {
return $.ajax({
url: 'MY URL',
data: {
'email': email
},
type: 'POST',
});
}
// function that expects a promise as an argument:
function displayData(x) {
x.success(function(realData) {
if (realData == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
//THAT VARIABLE IS STILL NOT WORKING OUTSIDE AJAX
error++;
}
});
}
// get a promise from testAjax:
var promise = testAjax();
// give a promise to other function:
displayData(promise);
if (error!=0)return;
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();
});
我如何解决这个问题?认为这个代码是正确的。
答案 0 :(得分:2)
尝试
$('.login').submit(function(e) {
e.preventDefault();
var error = 0;
var email = $email.val();
// function that makes a request and returns a promise:
function testAjax() {
return $.ajax({
url: 'MY URL',
data: {
'email': email
},
type: 'POST',
});
}
var error = 0;
var promise = testAjax();
function displayData(x) {
return x.then(function(realData) {
if (realData == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
//THAT VARIABLE IS STILL NOT WORKING OUTSIDE AJAX
error++;
}
}, function(jqxhr, textStatus, errorThrown) {
console.log(errorThrown)
});
};
displayData(promise).then(function(data) {
// if (error !=0 ) return;
// evaluate `error` status here ,
// do stuff
});
function test() {
return $.ajax("https://gist.githubusercontent.com/guest271314/6a76aa9d2921350c9d53/raw/49fbc054731540fa68b565e398d3574fde7366e9/abc.txt")
};
var error = 0;
var promise = test();
function displayData(x) {
return x.then(function(realData) {
if (realData) {
console.log("Błąd! taki email już istnieje w bazie!")
//THAT VARIABLE IS STILL NOT WORKING OUTSIDE AJAX
error++;
}
}, function(jqxhr, textStatus, errorThrown) {
console.log(errorThrown)
});
};
displayData(promise).then(function(data) {
if (error !== 0)
console.log(error)
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;