2015-08-09 34 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它甚至牵强之前