我正在尝试解析JSON。我正在使用
$getJSON
获取文件并将其内容保存到变量
JSONfile
,然后我将其传递给解析函数,但在getJSON函数之外它包含一个null并且在其中,它包含正确的数据,即使是变量
JSONfile
是全局声明的(我认为是)。我是Javascript初学者。请解释这里发生的事情,或者指出类似的东西(找不到自己)。
var atlasJSON = "http://127.0.0.1:8000/sprites/SPRITE.json";
var JSONfile = null;
function setup(){
body = document.getElementById('body');
canvas = document.createElement('canvas');
spriteManager = new SpriteSheetClass();
spriteManager.load(spritesheet);
$.getJSON(atlasJSON, function(data) {
JSONfile = data;
console.log(JSONfile); // JSON file content is here
});
console.log(JSONfile); // null !!!
debugger;
spriteManager.parseAtlasDefinition(JSONfile);
for(var i=0; i<spriteManager.sprites.length ; i++){
console.log(spriteManager.sprites[i]);
}
//canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
canvas.setAttribute('width', 1024);
canvas.setAttribute('height',800);
body.appendChild(canvas);
};
答案 0 :(得分:2)
您需要在回调中使用json
$.getJSON(atlasJSON, function(data) {
JSONfile = data;
console.log(JSONfile); // JSON file content is here
console.log(JSONfile); // null !!!
debugger;
spriteManager.parseAtlasDefinition(JSONfile);
for(var i=0; i<spriteManager.sprites.length ; i++){
console.log(spriteManager.sprites[i]);
}
//canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
canvas.setAttribute('width', 1024);
canvas.setAttribute('height',800);
body.appendChild(canvas);
});
答案 1 :(得分:2)
$ .getJSON是异步的,这意味着你打电话:
$.getJSON(atlasJSON, function(data) {
JSONfile = data;
console.log(JSONfile); // JSON file content is here
});
然后
console.log(JSONfile); // JSONfile is null...
这是预期的行为。只有在调用函数(数据)时,JSON才可用。
函数getJSON不会阻止代码执行。 它将通过网络将请求发送到服务器,并等待返回数据。代码现在将继续在下一行代码(在您的情况下为console.log)上执行,依此类推,直到收到来自远程服务器的数据。一旦完全接收到这样的数据,它将调用该函数。
您可以在函数中执行的操作,一旦返回就将JSON分配给全局变量,以便您可以在代码中的任何位置访问它,即
var JSONData = null;
然后调用函数(data)将其分配给变量。这种方式(并且只调用一次函数(数据))它可用于所有JavaScript代码。
答案 2 :(得分:-1)
您还需要将变量解析为函数
var JSONfile = null;
function setup(JSONfile){
body = document.getElementById('body');
canvas = document.createElement('canvas');