【问题标题】:Access class variable in jqueryjquery中的访问类变量
【发布时间】:2012-11-06 02:35:21
【问题描述】:

我的 html 中有一个选择,并希望在页面加载时通过 ajax 添加选项。选项值在我的数据库中,我通过调用 ajax 来获取它们。为此,我正在用 javascript 编写一个类,但是在它运行时我无法获取我的数据。请看:

--- Main.js ---

function MyLoader() {
    this._clients = null;
    this._code = null;
}

Loader.prototype = {

    var context = this;

    loadClients: function() {
        $.ajax({
            url: "my/php/",
            type: "POST",
            data: {...},
            success: function(response) {
                context._clients = response;
            }
        });
    },

    getCode: function() {...}
};

然后我有以下内容:

$(document).ready(function() {
    var loader = new Loader();
    loader.loadClients();
    alert(loader._clients);

    //Here I want to add my options to the select
});

我的警报总是返回 null,我不明白为什么。我需要将我的数据保存在课堂上,以便在需要时随时访问它们。

你能给我指出正确的方向,让我的所有东西都能正常工作吗?谢谢你的回答。

【问题讨论】:

    标签: javascript jquery ajax class


    【解决方案1】:
    Loader.prototype = { //     v---callback parameter
        loadClients: function(callback) {
            $.ajax({
                url: "my/php/",
                context: this, // <---set success context
                type: "POST",
                data: {...},
                success: callback // <---pass callback
            });
        },
    
        getCode: function() {...}
    };
    
    $(document).ready(function() {
        var loader = new Loader();
                          //  v---pass callback
        loader.loadClients(function(response) {
            this._clients = response;
            alert(this._clients);
            //Here I want to add my options to the select
        });
    
    });
    

    【讨论】:

      【解决方案2】:

      我相信您需要在“成功”回调中完成所有动态加载,因为它是异步加载的。

      【讨论】:

        【解决方案3】:

        您需要在成功回调中执行此操作,因为它是异步的:

        Loader.prototype = {
        
            var context = this;
        
            loadClients: function() {
                $.ajax({
                    url: "my/php/",
                    type: "POST",
                    data: {...},
                    success: function(response) {
                        context._clients = response;
                        alert(loader._clients);
        
                       //Here I want to add my options to the select
                    }
                });
            },
        
            getCode: function() {...}
        };
        
        $(document).ready(function() {
            var loader = new Loader();
            loader.loadClients();
        });
        

        【讨论】:

          猜你喜欢
          • 2018-08-21
          • 1970-01-01
          • 2011-08-28
          • 1970-01-01
          • 2017-11-21
          • 1970-01-01
          • 2013-12-21
          • 2011-10-31
          相关资源
          最近更新 更多