【发布时间】:2012-01-07 10:32:41
【问题描述】:
我无法访问实例化类的属性。该属性是使用 AJAX 调用设置的。
我正在尝试定义类“CurrentUser”,然后使用 AJAX 设置属性“userId”。
这里我定义了 CurrentUser 类,并赋予它 userID 属性:
function CurrentUser() {
// Do an ajax call to the server and get session data.
$.get("../../build/ajaxes/account/get_user_object_data.php", function(data) {
this.userId = data.userId;
console.log(data.userId); // This will correctly output "1".
}, "JSON");
}
这里我实例化了一个名为 billybob 的 CurrentUser。请注意我是如何无法输出 billybob 的属性:
// Instantiate the user.
var billybob = new CurrentUser();
console.log(billybob.userId); // This will incorrectly ouput "undefined".
我检查了 AJAX 的常见错误:
AJAX 调用以 JSON 对象的形式正确返回数据。我可以在 Firebug / 网络控制台中读取正确的对象。 AJAX 调用的状态也为“200”和“OK”。
我可以正确记录 AJAX 调用的数据,如我记录 data.userId 的代码的第一部分所示。
【问题讨论】:
-
我在想,也许“this.userId”不是指对象,而是指 AJAX 调用?
-
即使
this引用了您想要的内容,new CurrentUser()也会在 Ajax 方法之前返回。
标签: javascript jquery ajax object attributes