2015-08-09 38 views
4

我不確定這是否曾被問過,唯一類似的項目我發現was this。 將alert()更改爲console.log()會導致我的代碼失敗。第24行(緊隨xmlhttp.send()後)是斷行,我找不到原因。與console.log交換警報導致代碼失敗

function readFile() 
{ 
var xmlhttp = new XMLHttpRequest(); 
var totalBudgeted = 0; 
var totalSpent = 0; 
var fileJSON = {}; 
var url = 'gamedata.json'; 

xmlhttp.onreadystatechange = function() 
{ 
    if(xmlhttp.readyState == 4) 
    { 
     //alert('XMLHttpRequest status code: ' + xmlhttp.status); 
     // I am commenting this out so that I do not lose points for this assignment. However, FireFox will return a status of 200 when serving a local file. 
     //if(xmlhttp.status == 200) 
     { 
      fileJSON = JSON.parse(xmlhttp.responseText); 
     } 
    } 
} 
xmlhttp.open('GET', url, true); 
xmlhttp.send(); 

alert(fileJSON); 
for(var key in fileJSON) 
{ 
    if(fileJSON.hasOwnProperty(key)) 
    { 
     alert(key + " -> " + fileJSON[key]); 
    } 
} 
// Add up the column totals, and add the 'Total' row to fileJSON. 
for(var rowCount in fileJSON) 
{ 
    totalBudgeted += fileJSON[rowCount].budgeted; 
    totalSpent += fileJSON[rowCount].spent; 
    console.log('!!!!!!!!!!!!!!!rowCount: ' + rowCount); 
} 
jsonToHtml(fileJSON); 
} 

回答

6

把警報有明顯給人的異步得到足夠的時間來完成你處理響應

沒有警報之前,你的代碼處理fileJSON它甚至牽強之前