Jquery ajax存储变量,然后稍后检索

jquery ajax store variable and then retrieve later on

本文关键字:检索 然后 ajax 存储 变量 Jquery      更新时间:2023-09-26

嗨,我使用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());
 });

任何想法我怎么能得到这个全局分配的变量在这个函数之外?

change this

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对象中。当param未定义时,它将返回未更新的值,如果没有,它将首先更新它,然后返回它。

一个更优雅的解决方案是在这里使用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.
}

如果你需要一个全局变量,那么在文档之前声明这个变量。准备好了,因为在这个函数中定义的变量只在这个函数

中有效

Javascript作用域示例