全局变量不会填充来自ajax调用的数据

时间:2018-05-20 09:45:25

标签: jquery ajax global-variables local-variables

我不知道自己做错了什么,但是当您使用var在全局范围内声明变量然后稍后在本地范围内添加一个值时,不应该填充该变量。全球范围也是?因为当ajax调用之外的console.log $jUser是空对象时。

  // Initialize variables
    var $jUser = {};
    var $ajUsers = [];

    // Login POST 
    $('#frm-login').submit(function (e) {
        event.preventDefault()
        $loginButton.text('Please wait ...').prop('disabled')
        $.ajax({
            url: "/login-user",
            type: "POST",
            data: $('#frm-login').serialize(),
            dataType: "json"
        }).always(function (response) {
            $loginButton.text('Logging in').prop('disabled')
            console.log("Login", response)
            if (response.status == "error") {
                $loginButton.removeClass('lime').addClass('red').text('Log in failed. Try again.');
                return
            }
            sessionStorage.setItem('token', response.token)
            if (sessionStorage.token) {
                $.ajax({
                    type: "GET",
                    url: "/verify-user",
                    headers: {
                        'Authorization': 'Bearer ' + sessionStorage.token
                    },
                    dataType: "json"
                }).always(function (response) {
                    console.log("Auth", response)
                    if (response.status == "error") {
                        $loginButton.removeClass('lime').addClass('red').text('Log in failed. Try again.');
                        return
                    }
                    $('#index-page').css('display', 'none')
                    $('#main-page').css('display', 'block')
                    $jUser = response.authData.user
                    //console.log($jUser)
                })
            }
        })
    })
    console.log($jUser)

// ADDED

if (sessionStorage.token) {
        (function userSession() {
            $('#index-page').css('display', 'none')
            $('#main-page').css('display', 'block')
            $userAvatar.attr('src', $jUser.avatar)
            $userFullname.text($jUser.first_name + ' ' + $jUser.last_name)
            console.log('hello')
        })()
    }

0 个答案:

没有答案