简体   繁体   中英

jQuery AJAX received data is null outside of the success-handler

Consider this code example:

var source = null;

$.ajax({
    [...],
    success:function(data)
    {
        source = data;
        alert(source);
    }
});

alert(source);

Now: inside of the success handler, everything is fine, I get the correct data from the webservice and everything is just great. But as soon as JS leaves the $.ajax and is done with it the variable source is null again.

Tell me why. It must be some JavaScript specfic stuff I'm not familiar with. :/

It is probably because you are forgetting AJAX is asynchronous. The source variable will be undefined until the success callback is completed.

Doing alert(source) beneath that code (outside of the $.ajax() ) is almost guaranteed to be undefined .

Well, are you sure the success callback is called before the alert outside of the ajax call is triggered?

The ajax call is asynchronous and returns immediately.

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