如何从getJSON命令外部访问我的数据?
//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"
谢谢!
答案 0 :(得分: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);