jquery ajax 存储变量,稍后检索

jquery ajax store variable and then retrieve later on

您好,我正在使用 jquery 和 ajax 来检索已登录用户的用户 ID,我将其保存到一个变量中,因为我希望以后能够用它做一些逻辑在。但是我无法访问它。我的代码如下:

$(document).ready(function () {
    var taskBoard = {
       fetch: function (url, data) {

        $('.loading-icon').fadeIn();
        $('.task_board').addClass('loading');


        $.ajax({
            url: url,
            async: true,
            dataType: 'json',
            data: data,
            type: 'POST',
            success: function (json) {
                $('.loading-icon').fadeOut();
                $('#task_board').html($(json.data.taskBoard));
                $('.task_board').removeClass('loading');
                $('.update-results').hide();

            } // end success
        }); //end ajax
    }, //end fetch function

    authUser: function (url, data) {
        $.ajax({
            url: url,
            async: true,
            dataType: 'json',
            data: data,
            type: 'POST',
            success: function (json) {
                $.each($(json), function (index, item) {
                    taskBoard.storeUser(item.id);
                });


            } // end success
        }); //end ajax

    }, //end authUser function

    storeUser: function (param) {
        var authUserId = param;
        return param;
        // if I do an alert here the correct user id is returned.
    },

} //end var taskBoard

      //However if I do an alert here  outside of the var taskBoard I get an undefined. 

     alert(taskBoard.storeUser());
 });

我有什么想法可以在这个函数之外获得这个全局分配的变量吗?

好吧,如果你需要一个全局变量,那么在 document.ready 之前声明那个变量,因为在这个函数中定义的变量只在这个函数中有效

Javascript Scope Examples

改变这个

storeUser: function (param) {
    var authUserId = param;
    return param;
    // if I do an alert here the correct user id is returned.
},

改为:

authUserId : null,
storeUser: function (param) {
    if (param)
    {
        this.authUserId = param;
    }
    return this.authUserId;
},

现在 var authUserId 将作为 属性 存储在 taskBoard 对象中。 当参数未定义时,它将 return 未更新的值,如果没有,它将首先更新它然后 returns 它。

更优雅的解决方案是在此处使用 Object.defineProperty

删除 storeUser 属性 并在 taskBoard 对象声明后添加:

Object.defineProperty(taskBoard, "storeUser", {
    get : function(){ return this.StoreUserVar; },
    set : function(value){ this.StoreUserVar = value; }
});

现在您可以使用以下方式分配用户标识:

taskBoard.storeUser = item.id;

//-------- taskBoard object
        success: function (json) {
            $.each($(json), function (index, item) {
                taskBoard.storeUser = item.id;
                doOtherFunction();
            });
//--------

function doOtherFunction()
{
    //the callback function fired from the success.
    alert(taskBoard.storeUser); //this will alert with the value set.
}