Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 函数中的jquery变量范围_Javascript_Jquery_Variables_Scope - Fatal编程技术网

Javascript 函数中的jquery变量范围

Javascript 函数中的jquery变量范围,javascript,jquery,variables,scope,Javascript,Jquery,Variables,Scope,我一直在修补这个有一段时间,并没有真正得到它。我所有的jquery函数都有这个问题,所以这是我还没有学会的基本问题,也没有幸运地找到答案。getJSON方法是异步的。执行将继续执行下面的语句。当服务器响应请求时,回调函数将在一段时间后执行 因此,任何依赖于异步请求结果的代码都需要在回调函数中移动 这就是实际发生的情况: meclass.prototype.switch = function() { var items = []; $.getJSON('http://localhost/jsone

我一直在修补这个有一段时间,并没有真正得到它。我所有的jquery函数都有这个问题,所以这是我还没有学会的基本问题,也没有幸运地找到答案。

getJSON方法是异步的。执行将继续执行下面的语句。当服务器响应请求时,回调函数将在一段时间后执行

因此,任何依赖于异步请求结果的代码都需要在回调函数中移动

这就是实际发生的情况:

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