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
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)
})
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
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
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:
Use a temporary variable storage in
setA
. The AJAX insetA
uses synchronous request. After success, the value is stored in the temporary variable, and then the temporary variable is returned bysetA