2012-10-14 77 views
2
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 
} 

我一直在修補這一點,並沒有真正得到它。我在我所有的jquery函數中都遇到了這個問題,所以這是一些基本的東西,我只是沒有學過,而且還沒有找到答案。jquery功能範圍內的變量範圍

+2

項目數組是當你試圖訪問它空。只有當您從服務器接收到JSON對象時纔會填充它。因此,在你的回調中,一切正常。 – skovalyov

回答

7

getJSON方法是異步。執行將立即繼續執行以下說明。只要服務器響應請求,回調函數將在一段時間後執行。

因此,任何依賴於異步請求結果的代碼都需要在回調函數中移動。

這實際上是發生了什麼:

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