2011-05-13 6 views
1

일부 계단식 드롭 다운 목록에서 데이터를 업데이트하는 데 jQuery 메서드 $.getJSON을 사용하고 있습니다. 특히 드롭 다운에 대해 반환 된 것이없는 경우 (예 : 기본값). "없음".jQuery/javascript 기본 로직 질문

필자는 논리가 어떻게 바뀌어야하는지 명확히하고 싶습니다.

var hasItems = false; 
$.getJSON('ajax/test.json', function(data) { 
hasItems = true; 

    //Remove all items 
    //Fill drop down with data from JSON 


}); 

if (!hasItems) 
{ 
    //Remove all items 
    //Fill drop down with default value 
} 

그러나 나는 이것이 옳다고 생각하지 않습니다. 그렇다면 데이터 수신 여부에 관계없이 기능에 들어가야합니까? 데이터 객체에 무언가가 있는지 확인하고 싶습니다. 내 부울 값을 설정하려면 hasItems.

답변

6

콜백 함수에서 바로 확인을 처리해야하며 the example here을 확인하십시오.

var hasItems = false; 
$.getJSON('ajax/test.json', function(data) { 
hasItems = true; 

    //Remove all items 
    //Fill drop down with data from JSON 
if (!hasItems) 
{ 
    //Remove all items 
    //Fill drop down with default value 
} 

}); 
6

콜백 내부에서 반환 된 데이터를 모두 확인하려고합니다. 그렇지 않으면 콜백이 호출되기 전에 해당 조건이 호출되어 항상 할당 된 초기 값이됩니다.

1

당신은 비동기 상대하고, 그래서 당신은 당신이 타임 라인으로 작성하는 코드를 생각해야합니다

+ Some code 
+ Fire getJSON call 
| 
| server working 
| 
+ getJSON call returns and function runs 

함수 내부의 코드는 외부 코드 이후에 발생합니다. 일반적으로

:

// Setup any data you need before the call 

$.getJSON(..., function(r) { //or $.ajax() etc 
    // Handle the response from the server 
}); 

// Code here happens before the getJSON call returns - technically you could also 
// put your setup code here, although it would be weird, and probably upset other 
// coders.