2013-02-19 98 views
0

如何從getJSON命令之外訪問我的數據?加載後訪問jquery json數據?

//LOAD JSON 
$.getJSON("users.js", function(data) { 
    numberOfPieces = data.users.length; 
    alert("Loaded "+numberOfPieces); // <------WORKS 
}); 

//Select a piece 
var pieceSelected = Math.floor(Math.random() * (numberOfPieces)); 
alert("pieceSelected: "+data.users[pieceSelected].Name); // <------RETURNS "data is not defined" 

謝謝!

回答

1

你的問題是函數參數的作用域是該函數的範圍,並且在函數之外不可訪問。通過使用範圍外的變量,事情應該按預期工作。

var piecesData; 

//LOAD JSON 
$.getJSON("users.js", function(data) { 
    piecesData = data; 
    numberOfPieces = data.users.length; 
    alert("Loaded "+numberOfPieces); // <------WORKS 
}); 

//Select a piece 
var pieceSelected = Math.floor(Math.random() * (numberOfPieces)); 
alert("pieceSelected: "+ piecesData.users[pieceSelected].Name);