`var a =1;
function setA(){
$.get('http://localhost/','a=2',function(ret){
return ret.a;
});
}`
How to make function setA return the value of ret.a obtained using ajax?
怪我咯2017-06-26 10:52:25
Two ways
1: Change ajax to synchronization, and you can directly obtain the correct return value.
2: Add your processing logic directly to the ajax callback
怪我咯2017-06-26 10:52:25
Add a function parameter callback to getA, and then use callback(set.a) in the ajax return value.
zAccess set.a like this when using getA: getA(function(a){console.log(a)})
Examples are as follows:
var a =1;
function setA(callback){
$.get('http://localhost/','a=2',function(ret){
callback(ret.a);
});
}
setA(function(a) {
console.log('a:' + a)
})
仅有的幸福2017-06-26 10:52:25
var a;
$.get('http://localhost/','a=2',function(ret){
setA(ret.a); });
function setA(value){
a=value;
}
function getA(){
return a;
}
高洛峰2017-06-26 10:52:25
Use a temporary variable storage in setA
. The AJAX in setA
uses synchronous request. After success, the value is stored in the temporary variable, and then the temporary variable is returned by setA
setA() {
var temp = '';
$.get({
url: 'http://localhost/',
data: {a: 2},
async: false,
success: function(ret) {
temp = ret.a;
return ;
}
});
return temp;
}