声明一个javascript对象。 然后使用jQuery和Ajax设置属性

我无法访问实例化类的属性。 使用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 / Network控制台中读取正确的对象。 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将不知道你从哪里得到你的回调函数,所以它不能为你自动设置它。

你必须做的是保存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. IE billybob. console.log(data.userId, self.userid); // This will correctly output "1". }, "JSON"); } 

另请注意:

  var billybob = new CurrentUser(); console.log(billybob.userId); 

当您在创建billybob之后立即调用console.log (IE后)时,ajax请求尚未完成,因此undefined

在构造函数中,考虑做

 var self = this; 

并在function

 self.userId = data.userId; 

this内部function将不同于外部。 虽然,我不知道JQuery。 可能它应该自动设置关闭。