如何知道是否有人通过javascript登录? [英] how to know if someone is logged via javascript?

查看:51
本文介绍了如何知道是否有人通过javascript登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在php我会做

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

但是在javascript中如何查看?

But in javascript how can I check it?

谢谢

推荐答案

没有向服务器发出请求就没有可靠的方法,因为会话可能有在服务器端过期。在一个项目中,我执行以下操作,不完美的方式:

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

我说不完美,因为它会产生暂时锁定浏览器的同步请求。它的优点在于,可以从客户端应用程序的任何部分可靠地调用 checkAuth(),因为它强制浏览器在继续执行之前等待结果JS代码,但就是它。

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

这篇关于如何知道是否有人通过javascript登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆