简体   繁体   中英

jQuery AJAX callback does not set variable before function returns?

I have a function:

var foo=function(){
var ret="false";
var data={};
data["blah"]="blah";
  $.ajax({

          type: "POST",

          url: "https://website.com/a",

          data: data,

          dataType: "json"

      }).success(function (data) {

          ret=data["stuff"];
         alert("set to "+ret);
      }).error(function (a, b, c) {
    alert("error");
        ret="false";
      });
return ret;
}

when I do the following: alert(foo());

I get the follow order of output:

1.false

2.set to true

I was expecting to get ret set to true and then returning false, but this is not what's happening. What am I doing wrong?

The $.ajax is async by default. So basicly you return ret; earlier then javascript set it to ajax response.

Try to use async: false in $.ajax call options.

You cannot do this. The function will return before the AJAX call completes. It's asynchronous.

You cannot return from an AJAX function. I suggest moving all logic related to this AJAX call into the callback.

Your success callback function will be called when the ajax response is received. This could be many milliseconds later, depending on network round-trip time. Your foo function does not wait for the callback to complete, but moves on immediately.

If you have actions to take that need the results of your AJAX call, you will need to perform those actions inside your success callback. This will probably require you to restructure your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM