iT邦幫忙

2021 iThome 鐵人賽

DAY 21
1
永豐金融APIs

釋放你的潛能用技能交易吧!系列 第 21

[Day21] 第二十一章 - 使用Ajax來做登入API界接

前言

昨天我們把登入頁面套上了bootstrap
我們這次把jqury補上去
接者透過ajax做登入
回傳到profile.blade.php 顯示使用者資料

目標

  1. Jquery 套件使用
  2. Ajax 與前後端界接
  3. 前後端導向以及頁面轉換

實作

1. login.blade.php

我們先在上方新增jquery的資源link, 在head裡面

<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"> </script>
    </style>
</head>

接者我們要修改**button的type **把submit改成button
非常重要!! 因為submit會強制跳轉
button則可以依照自己的js操作來決定後續處理

<form class="form-signin" action="/test" method="POST">
        <!-- @csrf -->
        <img class="mb-4" src="https://images.unsplash.com/photo-1495360010541-f48722b34f7d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=436&q=80" alt="" width="72">
        <h1 class="h3 mb-3 font-weight-normal">請輸入使用者名稱及密碼登入</h1>
        <label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" id="inputEmail" name="email" class="form-control" placeholder="Email address" required autofocus>
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" id="inputPassword" name="passowrd" class="form-control" placeholder="Password" required>
        <button class="btn btn-lg btn-primary btn-block" type="button" id="login">Sign in</button>
        <p class="mt-5 mb-3 text-muted">© 2021 iThome 鐵人賽</p>
    </form>

最後我們在body後方補上script也就是ajax的code

<script>
        $(document).ready(function() {
            $("#login").on('click', function() {
                var data = {
                    email: $('#inputEmail').val(),
                    password: $('#inputPassword').val()
                }
                $.ajax({
                        method: "POST",
                        url: "/login",
                        dataType: 'json',
                        data
                    })
                    .done(function(msg) {
                        const d = new Date();
                        const exdays = 10;
                        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
                        let expires = "expires=" + d.toUTCString();
                        document.cookie = "token" + "=" + msg.token + ";" + expires + ";" + "path=/";
                        // localStorage.setItem('accessToken', msg.token);
                        window.location.href = '/profile';
                    });
            });
        });
    </script>

這邊有幾個小重點可以跟大家說一下

  1. $(document).ready的用途

$(document).ready(function() 是為了讓DOM物件載入完成後使用的function
簡單來說就是當html都渲染完成後 我再決定要發生什麼事件!!
否則骨架都還沒出來人要怎麼做動作辣

  1. $.ajax

這邊我們可以照者官方的說明文件依序把url,data,method塞進去畫葫蘆就好
要注意的是在done這邊是跟後端要完資料後要做什麼事情

  1. document.cookie

通常我們在登入後會把回傳的token塞到localstorage或是cookie裡使用

  1. window.location.href

完成後重新導向

2. route新增路徑

我們在route的web.php檔案裡面新增

Route::get('profile', 'UserController@getProfile');

接者可以使用

php artisan make:controller UserController

來建立此Controller

這個步驟目的在於我們在login頁面取得token後導向profile頁面
並且把使用者資料呈現在profile畫面上

3. UserController 來決定動作

在 app/http/controller/usercontroller裡面

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDO;

class UserController extends Controller
{
    //
    public function getProfile(Request $request)
    {
        $token = $request->headers->all();
        if (empty($token['cookie'][0])) {
            return redirect('/user/login');
            // dd($token);
        }

        $user = $request->user();
        return view('user.profile', ['user' => $user]);
    }
}


這邊 是判斷如果cookie沒有token代表沒有登入過
如果有就把user取得資料並且導向user.proflie的view裡面
第二個參數是把user資料傳進去

4. user.proflie 的blade

在views資料夾裡面新增user資料夾並且建立profile.blade.php

<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"> </script>
    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <style>
        .box {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
        }
    </style>
</head>

<div class="box">
    <div>
        <table class="table">
            <thead class="thead-dark">
                <tr>
                    <th scope="col">id</th>
                    <th scope="col">姓名</th>
                    <th scope="col">email</th>
                    <th scope="col">會員建立時間</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        {{$user->id}}
                    </td>
                    <td>
                        {{$user->name}}
                    </td>
                    <td>
                        {{$user->email}}
                    </td>
                    <td>
                        {{$user->created_at}}
                    </td>
                </tr>

            </tbody>
        </table>
    </div>
</div>

{{}}花括號 可以把物件印出來
我們把物件立面的屬性一一取出來(name,id,email這些)
我們這邊把登入者的
名字,ID,email印出來
並套上bootstrap出來吧
https://ithelp.ithome.com.tw/upload/images/20211006/20121052xhMY5of0Hd.png


上一篇
[Day20] 第二十章 - 修改登入畫面 (使用bootstrap 4.6的範例)
下一篇
[Day22] 第二十二章 - 使用token驗證使用者並且透過ajax來建立技能
系列文
釋放你的潛能用技能交易吧!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言