Javascript变量在不应该重置时被重置

时间:2011-09-16 21:13:50

标签: javascript json

我有一个函数我正在调用加载配置文件,我需要检查是否有任何数据返回,如果不是,我需要警告配置文件不存在。

这是我的代码。

    // Get JSON data from server
  result = false;
function loadData(id) {
    $.get("modules/device/loadConfigurationData.php", {
        id : id
    }, function(response) {       
         for (var i =0; i < response.length -1; i++)
             if (response[i]) 
             {
                 settings[response[i].setting_name] = response[i].setting_value;     
                 result = true;
             } 
             else 
             {
                result = false;
             }                       
    }, 'json');
}

以下是加载配置文件的功能。请注意,配置文件对于CONFIG 1和CONFIG 2确实是dexist,而不是CONFIG 3和CONFIG 4。

   // Load Configuration 1
function config1() {   
    loadData(1)    
    alert(result);
    if (result) 
    {
        alert('CONFIG 1 Loaded');   
        configurationLoaded = true;      
    } 
    else 
    {
        alert('CONFIG 1 does not exist.');
    }  
}
// Load Configuration 2
function config2() {
    loadData(2)    
    alert(result);
    if (result) 
    {
        alert('CONFIG 2 Loaded');   
        configurationLoaded = true;      
    } 
    else 
    {
        alert('CONFIG 2 does not exist.');
    }              
}
// Load Configuration 3
function config3() {
    loadData(3)    
    if (result)
    {
        alert('CONFIG 3 Loaded');   
        configurationLoaded = true;      
    } 
    else 
    {
        alert('CONFIG 3 does not exist.');
    }           
   result = false;
}
// Load Configuration 4
function config4() {    
    loadData(4)    
    alert(result);
    if (result) 
    {
        alert('CONFIG 4 Loaded');   
        configurationLoaded = true;      
    } 
    else 
    {
        alert('CONFIG 4 does not exist.');
    }          
}

如果存在数据,则应加载配置数据,否则应返回false并显示警报,让用户知道配置文件不存在。由于某种原因,结果变量正在重置并使其无效。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

这不起作用,因为get是异步运行的。所以基本上你的结果变量很可能会在回调中设置result变量之前被警告。

loadData(2); would still be loading. 
alert(result); this would be called before result is populated.