涉及AJAX的函数不返回值 - jQuery [重复]

This question already has an answer here:

I have a document.ready function like this;

  function myfun(){
    var xx;
    $.ajax({
        type: 'POST',
        url: 'handler.php',
        cache: false,
        success: function(result) {
          xx = result;
        },
    });
    return xx;
  }


  var a;
  a = myfun();
  alert(a);

handle.php is set to echo 1234. But I am getting alert as "undefined". How can I fix this? Expected alert is "1234" (the reply from ajax handler).

</div>

It's asynchronous. Use a callback:

function myfun(){

    return $.ajax({
        type: 'POST',
        url: 'handler.php',
        cache: false
    });
}

myfun().done(function(data){
    console.log(data);
});

Or if you're using an old jQuery version without deferred objects:

function myfun(done){

    $.ajax({
        type: 'POST',
        url: 'handler.php',
        cache: false,
        success: done
    });
}

myfun(function(data){
    console.log(data);
});

https://stackoverflow.com/search?q=ajax+not+returning+data

Because you return the value before the ajax call can complete, ajax call are by default async, you can alert inside the success callback, at that point your variable will have the value you set:

function myfun(){
  var xx;
  $.ajax({
      type: 'POST',
      url: 'handler.php',
      cache: false,
      success: function(result) {
        xx = result;
        alert(xx);
      },
  });
}

myfun();

It is a problem of asynchronous calls. You can rewrite code such as:

var xx;
  var a;

  function myfun(){
    $.ajax({
        type: 'POST',
        url: 'handler.php',
        cache: false,
        success: function(result) {
          xx = result;
        },
    });
  }

 myfun();
 alert(xx);