使用console.log交换警报会导致代码失败

时间:2015-08-09 04:34:33

标签: javascript alert console.log

我不确定之前是否曾经问过这个问题,这是我发现的唯一类似的项目was this。 将alert()更改为console.log()会导致我的代码失败。第24行(紧跟xmlhttp.send()之后)是断行,我无法弄清楚原因。

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 );
}

1 个答案:

答案 0 :(得分:6)

将警报放在那里显然可以让异步 GET在处理响应之前有足够的时间完成

没有提醒,您的代码会在提取之前处理fileJSON

相关问题