开发者

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

开发者 https://www.devze.com 2023-02-18 04:46 出处:网络
Consider this code example: var source = null; $.ajax({ [...], success:function(data) { source = data; alert(source);

Consider this code example:

var source = null;

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

alert(source);

Now: inside of the success 开发者_如何学Gohandler, 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消