2011-09-16 5 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'); 
} 

다음은 구성 파일을로드하는 기능입니다. 시키는, 그렇지 않으면 false를 돌려, 그 구성 파일 CONFIG 1 및 구성 2 dexist을 수행하지만 데이터가 존재하는 경우이 구성 데이터를로드한다 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.'); 
    }   
} 

3 및 구성을 설정하지 참고 및 경고를 표시 사용자는 구성 파일이 존재하지 않는다는 것을 알고 있습니다. 어떤 이유로 인해 결과 변수가 재설정되어 작동하지 않게됩니다.

도움을 주시면 감사하겠습니다.

답변

2

get이 비동기 적으로 실행되기 때문에 작동하지 않습니다. 따라서 기본적으로 결과 변수는 콜백에 result 변수가 설정되기 전에 경고를 받게됩니다.

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