其它服務器(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;
    }

點擊退出按鈕,成功退出登錄!

然後玩幾遍登錄→退出。搞定!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章