[英]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. 现在:在成功处理程序中,一切都很好,我从Web服务获取了正确的数据,而一切都很好。 But as soon as JS leaves the $.ajax and is done with it the variable source is null again.
但是,一旦JS离开$ .ajax并完成它,变量source便再次为null。
Tell me why. 告诉我为什么。 It must be some JavaScript specfic stuff I'm not familiar with.
一定是我不熟悉的一些JavaScript特有的东西。 :/
:/
It is probably because you are forgetting AJAX is asynchronous. 可能是因为您忘记了AJAX是异步的。 The
source
variable will be undefined
until the success
callback is completed. 在
success
回调完成之前, source
变量将是undefined
的。
Doing alert(source)
beneath that code (outside of the $.ajax()
) is almost guaranteed to be undefined
. 在该代码下(在
$.ajax()
之外alert(source)
执行alert(source)
几乎可以保证是undefined
。
Well, are you sure the success callback is called before the alert outside of the ajax call is triggered? 好吧,您确定在触发Ajax调用之外的警报之前调用成功回调吗?
The ajax call is asynchronous and returns immediately. ajax调用是异步的,并立即返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.