分配后无法访问 Ajax 赋值的变量

Ajax-assigned variable inaccessible after assignment

本文关键字:赋值 变量 Ajax 访问 分配      更新时间:2023-09-26

所以,我有一个从SQL数据库获取数据的脚本,我正在尝试为它构建一个JS包装器。我使用以下函数来调用该脚本,并在准备就绪后立即使用数据库中的信息。

var User = function() {
    this.email = null;
    //Async call to get user values
    this.current(function(response) {
        this.email = response.email;
        //The value is assigned/usable at this point
    });
};
User.prototype.current = function(callback) {
    $.post("php/db_functions.php", {object: "CurrentUser"}).done(function(result) {
        callback(JSON.parse(result)[0]);
    });
};.

一切似乎都很好,但是如果我在创建对象后尝试从对象访问值,它会返回 undefined,如下所示:

var me = new User();
//And then, way after the async call and when me.email should be defined
me.email //Returns undefined

为什么我可以在回调中使用它,但之后不能使用它?

在函数中,上下文变量this指向全局window对象或严格模式下的undefined,除非调用方另有指定。因此,您需要在局部变量中捕获this的值:

//Async call to get user values
var that = this;
this.current(function(response) {
    that.email = response.email;
});

或者使用 callapply 方法在所需的上下文中调用函数:

User.prototype.current = function(callback) {
    var that = this;
    $.post("php/db_functions.php", {object: "CurrentUser"}).done(function(result) {
        callback.call(that, JSON.parse(result)[0]);
    });
};.

此外,正如其他人所提到的,不能保证 AJAX 请求在User构建器返回时已经完成。

这是一个计时错误,因为在异步调用返回之前不会分配变量。您无法立即访问电子邮件。