其它服务器(ThinkPHP5)与Discuz3.3自带的UCenter实现同步(三) - 同步登录、退出登录

UCenter的登录和退出登录与其它操作不同,它多了一步返回js代码,然后你需要将代码添加到前端页面,才能运行。
本篇所有操作都在tp项目下编辑。

复制下标1的,改成下标2再修改相关信息
在这里插入图片描述
新增登录方法

    public function login()
    {
        $uid = uc_user_login('username', '1');
        var_dump($uid[0]);
        if ($uid > 0){
            $result = uc_user_synlogin($uid[0]);
            var_dump($result);
        }
    }

在这里插入图片描述
string(1) "8"是用户id。
这里注意了!虽然第二个srting为空,但是它实际上是string(280),我在这儿被坑了。按我的习惯就是一看到“”就会觉得是没数据。。

我们加个htmlspecialchars函数把它输出出来

 public function login()
    {
        $uid = uc_user_login('username', '1');
        var_dump($uid[0]);
        if ($uid > 0){
            $result = uc_user_synlogin($uid[0]);
            var_dump(htmlspecialchars($result));
        }
    }

在这里插入图片描述
你可以复制src里的到浏览器运行,然后你会发现dz登录了!
但还没完,因为你现在是手动运行,你总不能反回这行,让用户自己操作吧?

那我们要如何把这js代码添加进前端页面呢?我们登录一般都是ajax请求吧?那本篇就以ajax来做示例。

新建index.html文件
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button id="but">登录</button>
<div id="script"></div>
</body>
</html>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
    $('#but').click(function(){
        $.post("{:url('index/index/login')}", '', function (data) {
            $('#script').append(data);
        })
    });
</script>

修改login方法

    public function login()
    {
        if (request()->isPost()) {
            $uid = uc_user_login('username', '1');
            if ($uid > 0){
                $result = uc_user_synlogin($uid[0]);
                return $result;
            }
        } else {
            return $this->fetch();
        }
    }    
    

dz退出登录
访问http://localhost/tp/public/index.php/index/index/login
点击tp的登录按钮,会发现已经同步登录了。

同步退出登录
在login.html新增退出登录按钮与ajax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button id="but">登录</button>
<button id="out">退出</button>
<div id="script"></div>
</body>
</html>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
    $('#but').click(function(){
        $.post("{:url('index/index/login')}", '', function (data) {
            $('#script').append(data);
        })
    });

    $('#out').click(function(){
        $.post("{:url('index/index/logout')}", '', function (data) {
            $('#script').append(data);
        })
    });
</script>

新增方法

    public function logout()
    {
        $result = uc_user_synlogout();
        return $result;
    }

点击退出按钮,成功退出登录!

然后玩几遍登录→退出。搞定!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值