search

Home  >  Q&A  >  body text

javascript - jquery ajax return value acquisition

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

怪我咯怪我咯2711 days ago688

reply all(4)I'll reply

  • 怪我咯

    怪我咯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

    reply
    0
  • 怪我咯

    怪我咯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)
        })

    reply
    0
  • 仅有的幸福

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

    reply
    0
  • 高洛峰

    高洛峰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;
    }

    reply
    0
  • Cancelreply