简体   繁体   中英

How can I access data returned from ajax call outside AJAX callback function in my case?

I have a function which generate ajax call to server:

function askServer(callback) = {
     $.ajax({
       // ...
       async: true, //I have to use true here
       success: function(response) {
         callback(response); //callback handle server response
       },

     });
  };

The function to handle server response:

function handleResponse(){
     var dataObject;
     askServer(function(response){

         //response is an object {car:{id:2, name:TOYOTA}}
         dataObject=response.car;
     });
    //Now, I would like to access the dataObject outside callback function
    //but if I make it like this, the dataObject value will be null because it is outside the callback

}

How can I access dataObject outside callback function as I indicated above? (the dataObject contain server response data)

I have to use async: true , I know I can get rid of the problem if I use async: false .

var dataObject;

function handleResponse() {
  askServer(function(response) {
    dataObject = response.car;
  });
}

This is a matter of assigning the values AFTER the callback returns. Any attempt at doing it before will only cause an "undefined" quirk.

Solution: Define your function outside of your.ajax call, then in your.ajax success function - call the function you defined PASSING the data that is returned.

If this isn't what you were looking for, please tell us how you resolved your issue. Also, your code is bit confusing, and you have a comma in your function(response). Perhaps you can clean it up if you have the solution to your original question, so others can find this post more useful.

BTW - async = true is default;)

Cheers.

If you "have to" do an async call then by definition you don't know how long it will be before the callback occurs. That's why the callback concept is used in that situation in the first place. All processing that needs to be done on the results of the async ajax call needs to occur in the callback (or in other functions called from the callback).

Other functions elsewhere on your page can test to see whether the results have come in yet - if the callback stores the result in a globally declared variable it obviously won't be usable until after the callback actually happens but in the mean time other code can test if that variable is null or undefined: if it is then you're still waiting for a response, but if there's a value you know the response has occurred.

Declare

var dataObject;

outside of the function as a global level variable. Then you can access it from any other function.

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