how to know if someone is logged via javascript?

前端 未结 4 1364
渐次进展
渐次进展 2021-01-03 08:43

in php i would do

if (isset($_COOKIE[\'user\']) && $_COOKIE[\'user\'] == $valueFromDb)
 echo \'logged\';

But in javascript how can

相关标签:
4条回答
  • 2021-01-03 09:21

    When you want to know if user is logged on a page to do some type of special action, I usually use a hidden input with a special name that is checked on js. If the user is logged you put that on a master page or something like that and then in js check if it exist to know if the user is logged.

    Something like:

    <input type="hidden" class="UserIsLogged" />
    <script type="text/javascript">
            if ($(".UserIsLogged").length > 0) {
                //User is logged
            }
    </script>
    
    0 讨论(0)
  • 2021-01-03 09:23

    There is no reliable way to do this without making a request to the server, since the session might have expired on the server side. In one project, I do it the following, imperfect way:

    checkAuth() {
        var logged = (function() {
            var isLogged = null;
            $.ajax({
                'async': false,
                'global': false,
                'url': '/user/isLogged/',
                'success': function(resp) {
                    isLogged = (resp === "1");
                }
            });
            return isLogged;
        })();
        return logged;
    }
    

    I say imperfect because it makes a synchronous request which temporarily locks up the browser. It does have an advantage in that checkAuth() can be reliably called from any part of the client-side application since it forces the browser to wait for the result before continuing execution of the JS code, but that's about it.

    The alternative, asynchronous (non-locking) approach would be to do something like this:

    $.ajax({
        'url': '/user/isLogged/',
        'success': function(resp) {
            if(resp === "1") {
                // do your thing here, no need
                // for async: false  
            }
        }
    });
    
    0 讨论(0)
  • 2021-01-03 09:30

    You are mixing up server-side processing (php) with client side processing (javascript). On the client side this information does not exist unless the server has provided it in some framework-specific way.

    0 讨论(0)
  • 2021-01-03 09:34

    Yes. check out this question: Create, read, and erase cookies with jQuery

    a plugin to make it even easier for you: http://plugins.jquery.com/project/cookie

    0 讨论(0)
提交回复
热议问题