AJAX-响应数据未保存到全局范围? [英] AJAX- response data not saved to global scope?
问题描述
我遇到了下面显示的行没有将变量存储到全局范围的问题:
I am having the issue of my below shown lines not storing the variable into the global scope:
var somedata;
$.ajax({
cache: false,
url: verification_url,
success: function(data){
somedata = data;
}
});
alert(somedata); // Undefined
我做错了什么?我需要把它包装成一个单独的函数还是什么?
What am I doing wrong? Do I need to wrap this into a separate function or what?
推荐答案
alert()
代码在收到来自 $.ajax
的响应之前运行.
The alert()
code runs before the response from $.ajax
is received.
这就是它未定义
的原因.
var somedata;
$.ajax({
cache: false,
url: verification_url,
success: function(data){
somedata = data;
alert( somedata ); // 2. this will occur after the response is received
}
});
alert(somedata); // 1. this will occur first
在这里您可以看到警报的发生顺序不正确.默认情况下,AJAX 请求不会阻止后续代码运行.
Here you can see that the alerts happen out of order. By default an AJAX request does not prevent subsequent code from running.
这就是拥有 回调 方法的全部目的.它是一种在适当的时候被调用的方法,而不是依赖于同步执行.
That's the entire purpose of having a callback method. It is a method that gets called at the appropriate time, instead of relying on synchronous execution.
这篇关于AJAX-响应数据未保存到全局范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!