2010-01-30 1 views
0

jQuery.getJSON() 호출이 JSON 배열로 전역 변수를 변경하려고합니다.로컬 함수에서 전역 변수를 변경할 수 없습니다.

var photo_info ; 

//Advance to the next image 
    function changeImage(direction) { 

      jQuery('img#preview_image').fadeOut('fast'); 
      jQuery('#photo_main').css('width','740px'); 

      if (direction == 'next') { 
        jQuery.getJSON('/ajaxupdate?view&sort='+sort+'&a='+a+'&s=' + title_url_next, function(data) { 
          photo_info = data; 
          title_url = photo_info.title_url;                       
          title_url_next = photo_info.preview_title_url_next;                   
          title_url_previous = photo_info.preview_title_url_previous;                 
        }); 
      } else if (direction == 'prev') { 
        jQuery.getJSON('/ajaxupdate?view&sort='+sort+'&a='+a+'&s=' + title_url_previous, function(data) { 
          photo_info = data; 
          title_url = photo_info.title_url; 
          title_url_next = photo_info.preview_title_url_next; 
          title_url_previous = photo_info.preview_title_url_previous; 
        }); 
      } 
} 

그러나 변수 photo_info는 getJSON() 함수에서만 액세스 할 수 있으며 undefined를 반환합니다. 스크립트의 다른 모든 곳에서.

내가 뭘 잘못 했니? 당신의 도움을 주셔서 감사합니다.

답변

1

는 Ajax 호출이 비동기 말했다. ajaxComplete 기능을 사용하거나 아약스 호출로해서 getJSON 함수를 교체하고 성공 기능 예컨대 : 이내에서 photo_info의 VAR를 사용

$.ajax({ 
    url: 'ajax/test.html', 
    success: function(data) { 
    $('.result').html(photo_info); 
    } 
}); 
1

changeImage이 반환 된 직후 스크립트의 나머지 부분에서 photoinfo을 보면 Ajax 호출이 비동기이기 때문에 값이없는 것입니다. 더 많은 이벤트를 주도하려면 응용 프로그램을 재고해야합니다.

+0

안녕 - photo_info 심지어 changeImage() 함수 내에서 액세스 할 수 없습니다. 감사. – ensnare

+0

changeImage 함수 내에서도 아약스 호출이 아직 반환되지 않았기 때문에 Randal이 맞습니다. 문제 해결 방법에 대한 내 대답을 참조하십시오. – pedro