javascript - jquery ajax return value acquisition
怪我咯
怪我咯 2017-06-26 10:50:25
0
4
700

`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?

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(4)
刘奇

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)
    })
仅有的幸福
var a;

$.get('http://localhost/','a=2',function(ret){
    setA(ret.a); });
function setA(value){
    a=value;
}

function getA(){
    return 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

setA() {
    var temp = '';

    $.get({
        url: 'http://localhost/',
        data: {a: 2},
        async: false,
        success: function(ret) {
            temp = ret.a;
            return ;
        }
    });
    
    return temp;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template