获取变量的ajax完成后, [英] Get a variable after ajax done
本文介绍了获取变量的ajax完成后,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个$ C $下做出一些要求我的服务器:
I have this code for make some request to my server:
function myAjaxCheck(token) {
$.ajax({
type: 'POST',
url: 'auth.php',
data: {
token: token,
},
dataType: 'json',
success: function (data) {
if (data.auth == 'OK') {
alert ('ok');
}
} else {
alert('Error: ' + data.auth);
}
}
}).done(function (data) {
return data;
});
}
所以,我需要返回的数据传递到像一个变量:
So, i need to pass the returned data into a variable like:
Var MyVariable = myAjaxCheck(token);
console.log(MyVariable);
在控制台:
未定义
哪里出了问题,应该将数据返回完成时,却并非如此。
at console:
undefined
Where is the problem, is supposed to data will returned when done, but isn't.
推荐答案
默认情况下,阿贾克斯()
请求是异步所以调用阿贾克斯()
通常会返回请求完成之前。你可以使用一个回调函数。
By default, an ajax()
request is asynchronous so the call to ajax()
will usually return before the request completes. You could make use of a callback function instead.
function myAjaxCheck(token, callback) {
$.ajax({
type: 'POST',
url: 'auth.php',
data: {
token: token,
},
dataType: 'json',
success: function (data) {
if (data.auth == 'OK') {
alert ('ok');
}
} else {
alert('Error: ' + data.auth);
}
callback(data);
}
});
}
var myVariable;
myAajxCheck(token, function(returnedData){ //anonymous callback function
myVariable = returnedData;
console.log(myVariable);
});
如果你绝对必须,您可以使用 异步:假
电话里面阿贾克斯()
。
If you absolutely must, you could use async: false
inside the call to ajax()
.
这篇关于获取变量的ajax完成后,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文