【问题标题】:Unable to change global variable from local function无法从局部函数更改全局变量
【发布时间】:2010-01-30 10:33:29
【问题描述】:

我正在尝试让 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。

我做错了什么?感谢您的帮助。

【问题讨论】:

    标签: javascript javascript-events jquery


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      如果您在changeImage 返回之后立即在脚本的其余部分查看photoinfo,那么它当然不会有值,因为Ajax 调用是异步的。您需要重新考虑您的应用程序,使其更加受事件驱动。

      【讨论】:

      • 嗨——即使在 changeImage() 函数中也无法访问 photo_info。谢谢。
      • Randal 是对的,因为即使在 changeImage 函数中,ajax 调用还没有返回。有关如何解决问题的选项,请参阅我的答案。
      【解决方案3】:

      JavaScript 作用域与标准作用域不太一样。由于嵌套函数,您实际上正在失去作用域。尝试阅读这篇文章:

      http://www.robertsosinski.com/2009/04/28/binding-scope-in-javascript/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-14
        • 1970-01-01
        • 2013-10-04
        • 1970-01-01
        • 1970-01-01
        • 2019-02-10
        • 1970-01-01
        相关资源
        最近更新 更多