0

这真让我抓狂。

它似乎无法从 AJAX 内部设置属性的值。

下面是我的代码

function Captcha(userKey) {
    var self = this;

    this.key;
    this.getCaptchaKey = function(userKey) {
        $.post('/api/captcha/get-key',data, function(data, status,jqXHR) {
            if(status) {
                self.key = data.data.captchaKey;

            }
        },"json");
    };
    this.getCaptchaKey(userKey);
}

我将“this”设置为“self”以从 AJAX 调用内部引用。

然后当我 console.log() 这个对象本身在对象之外时,它告诉我该值已经设置。

self.captcha = new Captcha(self.userKey);
    self.captchaKey = self.captcha.key

    console.log(self.captcha);

所以'self.captcha'返回从AJAX调用中设置的'key'正确值的对象。

但是当我 console.log(self.captcha.key) 时,它说'未定义'

我一直在到处搜索,但找不到答案。

4

1 回答 1

1

我认为您的问题是您将异步调用视为同步的事实。您正在 Ajax 调用返回之前读取该值。

于 2012-10-13T01:01:55.700 回答