2013-03-01 77 views
0

我無法讓我的代碼正常工作。我使用XMLHttpRequest加載並解析了JSON文件,該文件工作正常,但是在我的setup()函數之後,我無法對任何我定義的變量(如spriteDictionary)調用任何其他函數 - 即使在各種設置函數中,我可以讀取這些變量並且看起來都很好。JavaScript變量變得不明確

有什麼想法?在下面的示例中,當我調用console.log(parsedJSON)時;它出現了未定義,這是奇怪的,因爲我可以在我的設置代碼中讀取它的內容。謝謝!

<!DOCTYPE html> 

<html> 
<head> 
<title>Page Title</title> 
</head> 
<body id="body"> 
</body> 

<script type="application/x-javascript"> 
var parsedJSON; 
var ctx; 
var canvas; 
var atlas; 
var sprites = []; 
var spriteDictionary = {}; 

var sprite = function(name, atl, x, y, w, h) { 
    this.name = name; 
    this.atlas = atl; 
    this.x = x; 
    this.y = y; 
    this.w = w; 
    this.h = h; 
    this.cx = -w/2.0; 
    this.cy = -h/2.0; 

} 

function setup() { 
    var body = document.getElementById("body"); 

    canvas = document.createElement("canvas"); 
    canvas.width = 1200; 
    canvas.height =720; 
    body.appendChild(canvas); 

    var ctx = canvas.getContext('2d'); 

    ctx.fillStyle="#000000"; 
    ctx.fillRect(0,0,1200,720); 

    var xhr = new XMLHttpRequest(); 
    xhr.open("GET","game_gfx.json",true); 
    xhr.onload = function(){ 
     parsedJSON = JSON.parse(this.responseText); 
     load_assets(parsedJSON); 
    } 
    xhr.send(); 
    ctx = canvas.getContext('2d'); 

} 

function load_assets(pJSON) { 
    atlas = new Image(); 
    atlas.onload = function() { 
     console.log("atlas loaded"); 
    } 
    atlas.src= pJSON['meta']['image']; 
    var frame; 
    for (var i in pJSON['frames']){ 
     frame = pJSON['frames'][i]; 
     spriteDictionary[frame['filename']] = new sprite(frame['filename'],atlas,frame['frame']['x'],frame['frame']['y'],frame['frame']['w'],frame['frame']['h']); 
     i++; 
    } 
} 

setup(); 

console.log(parsedJSON); 

</script> 


</html> 
+0

什麼是'類型= 「應​​用程序/ x-的javascript」'的目的是什麼?只是把它留下。 – 2013-03-01 16:25:45

+0

目的是科莫多編輯自動把它扔進去,我懶得刪除它。 – Lucian 2013-03-01 18:01:16

回答

1

您不能將異步調用視爲同步調用。

在Ajax調用返回之前調用console.log行。

onload listener中的一個簡單的console.log語句會告訴你。

xhr.onload = function(){ 
    console.log("I AM HERE!"); 
    ... 

日誌看起來像

undefined 
"I AM HERE" 
"atlas loaded" 
+0

Ahhh謝謝。所以當我調用其他命令時,我的XHR還沒有完成。我很感激幫助。 – Lucian 2013-03-01 18:00:28