我无法访问实例化类的属性。该属性是使用 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。请注意我如何无法输出比利鲍勃的属性:
// 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 的代码的第一部分所示。
最佳答案
也许这就解决了:
在您的原始代码中:
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");
}
你正在创建一个匿名函数,稍后将由 jQuery 的内部调用 this
设置为 ajax 对象。所以 this
将是匿名函数内的 ajax 对象,而不是 billybob
。所以当
你做 this.userId = ...
this
意味着没有 userid 属性的 ajax 对象。
jQuery 不知道你从哪里得到你的回调函数,所以它不能自动设置 this
给你。
您必须做的是保存 billybob
(或任何 CurrentUser
实例)引用并在回调中使用它,如下所示:
function CurrentUser() {
var self = this;
$.get("../../build/ajaxes/account/get_user_object_data.php", function(data) {
self.userId = data.userId; //self refers to what this refered to earlier. I.E. billybob.
console.log(data.userId, self.userid); // This will correctly output "1".
}, "JSON");
}
另请注意:
var billybob = new CurrentUser();
console.log(billybob.userId);
当您调用 console.log
时(即在创建 billybob
之后),ajax 请求尚未完成,因此它是 undefined
.
关于javascript - 声明一个 javascript 对象。然后使用 jQuery 和 Ajax 设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8287834/