开发者

how to know if someone is logged via javascript?

in php i would do

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

But in javascript how c开发者_C百科an I check it?

Thanks


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  
        }
    }
});


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>


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜