2011-09-16 34 views
0

應該我有一個功能我打電話加載配置文件,我需要檢查是否有任何數據返回,如果不是我需要提醒的是,配置文件不存在。JavaScript變量被重置時,它不

這是我的代碼。

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

這裏是加載配置文件的函數。需要注意的是配置文件做dexist爲CONFIG 1和CONFIG 2,但不配置3和配置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並顯示警告,讓用戶知道配置文件不存在。出於某種原因,結果變量正在重置並使其無法工作。

任何幫助將不勝感激。

回答

2

因爲get是異步運行這將無法正常工作。所以基本上前result變量回調設置你的結果變量將最有可能被警告。

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