Javascript 函数中的jquery变量范围
我一直在修补这个有一段时间,并没有真正得到它。我所有的jquery函数都有这个问题,所以这是我还没有学会的基本问题,也没有幸运地找到答案。getJSON方法是异步的。执行将继续执行下面的语句。当服务器响应请求时,回调函数将在一段时间后执行 因此,任何依赖于异步请求结果的代码都需要在回调函数中移动 这就是实际发生的情况:Javascript 函数中的jquery变量范围,javascript,jquery,variables,scope,Javascript,Jquery,Variables,Scope,我一直在修补这个有一段时间,并没有真正得到它。我所有的jquery函数都有这个问题,所以这是我还没有学会的基本问题,也没有幸运地找到答案。getJSON方法是异步的。执行将继续执行下面的语句。当服务器响应请求时,回调函数将在一段时间后执行 因此,任何依赖于异步请求结果的代码都需要在回调函数中移动 这就是实际发生的情况: meclass.prototype.switch = function() { var items = []; $.getJSON('http://localhost/jsone
meclass.prototype.switch = function() {
var items = [];
$.getJSON('http://localhost/jsoner.php', function(data) {
$.each(data, function(key, val) {
items.push(val);
alert(items[0]); //this works
});
});
alert(items[0]); //this does not
}
尝试访问时,items数组为空。只有当您从服务器接收JSON对象时,才会填充它。因此,在回调中,一切正常。
var items = []; //Declare `items`, empty array
//Make AJAX request
alert(items[0]); //It's still an empty array
//Wait some arbitrary amount of time...
//AJAX request complete, run the callback function
alert(items[0]); //Inside callback, items now contains elements