0

如何从 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"

谢谢!

4

1 回答 1

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);
于 2013-02-19T21:56:43.883 回答