how to know if someone is logged via javascript?

前端 未结 4 1379
渐次进展
渐次进展 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条回答
  •  梦毁少年i
    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  
            }
        }
    });
    

提交回复
热议问题