2017-12-10 1 views
0

JS R 드 API의 JSON 파일에서 JS 코드에서 사용할 수있는 로컬 사전 변수에 특정 요소를 쓰려고합니다. 내 AJAX GET 요청을 잘 작동하지만 AJAX 요청 외부 변수를 인쇄 할 때 코드 외부에서 얻은 데이터에 액세스 할 수 없습니다, 정의되지 않은 반환합니다. 나는 콜백 함수를 사용하여이 작업을해야한다는 것을 알고 있지만 제대로 수행 할 수 없다. 이것은 내가 콜백 기능을 사용하기 전에 어떻게 생겼는지입니다 :ajax GET 요청과 함께 작동하는 콜백 함수를 얻을 수 없습니다.

<script> 

var LeagueTable = [] 

    $.ajax({ 
     url: 'http://api.football-data.org/v1/competitions/445/leagueTable/?', 
     headers: { 
      'X-Auth-Token':'' 
     }, 
     method: 'GET', 
     dataType: 'json', 
     success: function(data) { 
     console.log(data) 
     for (i = 0; i < 20; i++) { 
     LeagueTable[data.standing[i].teamName] = data.standing[i].position 
     } 
} 
    }); 


// LeagueTableAppend(LeagueTable) 
console.log(LeagueTable["Watford FC"]) 

</script> 

을하지만 사전이 아약스 요청 이외의 추가되지 않습니다, 그래서 콜백 기능이 변경 시도,하지만 난 방법을 정말 잘 모르겠어요 그들을 구현하십시오. LeagueTable 사전이 for 루프에 추가 된 값을 유지하기를 원했습니다. 그리고 나서 이것이 콜백 함수를 사용하려는 제 시도 였지만 작동하지 않습니다.

<script> 

var LeagueTable = [] 

function getdata(){ 
    $.ajax({ 
     url: 'http://api.football-data.org/v1/competitions/445/leagueTable/?', 
     headers: { 
      'X-Auth-Token':'' 
     }, 
     method: 'GET', 
     dataType: 'json', 
     success: handleData 

    }); 
    } 


function handleData(data){ 
    // console.log('success: '+ JSON.stringify(data)); 
    for (i = 0; i < 20; i++) { 
    LeagueTable[data.standing[i].teamName] = data.standing[i].position 
    // console.log(JSON.stringify(data.standing[i].teamName) + ':' + data.standing[i].position); 
          } 
         } 
getdata(handleData) 
// LeagueTableAppend(LeagueTable) 

console.log(LeagueTable["Watford FC"]) 
</script> 
+0

시간이 오래되었습니다. 예를 들어 [here] (https://stackoverflow.com/questions/10652887/is-it-posible-to-use-ajax-respone-outside-of-it) 또는 [여기] (https : // stackoverflow. co.kr/questions/21052258/passing-data-outside-ajax-call-jquery) ... – dhilt

답변

0

콜백 코드는 요청이 반환되면 실행되지만 요청이 전송 된 후 곧바로 인쇄 코드가 실행됩니다.

관련 문제