我正在尝试让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;
                    });
            }
}


但是,只能从getJSON()函数中访问变量photo_info,并从脚本中的其他任何位置返回未定义的变量。

我究竟做错了什么?谢谢你的帮助。

最佳答案

正如Randal所说,Ajax调用是异步的。使用ajaxComplete函数或将getJSON函数替换为.ajax调用,并在成功函数中使用photo_info var,例如:

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

关于javascript - 无法从局部功能更改全局变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2166426/

10-12 12:47
查看更多