login.html的程式碼範例
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.5/sweetalert2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.5/sweetalert2.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/style.css">
<title>登入頁面</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<h1 style="text-align:center"><img src="/images/logo.png" alt=""></h1>
<hr>
<form>
<div id="tips"></div>
<label for="username">帳號</label>
<input type="text" class="form-control" name="username" id="username" placeholder="請輸入帳號" title="請輸入4~20位的英數字或_" pattern="^\w{4,20}$" />
<br>
<label for="password">密碼</label>
<input type="password" class="form-control" name="password" id="password" placeholder="請輸入密碼" title="請輸入6~20位的英數字或_" pattern="^\w{6,20}$" />
<br>
<button type="submit" class="btn btn-primary btn-lg btn-block">登入</button>
<br>
</form>
<hr> 還沒有帳號? <a href="/register">註冊</a>
</div>
</div>
</div>
<script>
$(function () {
$("form").submit(function (e) {
e.preventDefault();
var username = $("form input[name=username]").val(),
password = $("form input[name=password]").val();
$.ajax({
type: "post",
url: "/login",
data: {
username: username,
password: password
},
dataType: "json",
success: function (response) {
switch (response.code) {
case 200:
location.href = "/";
break;
case 400:
$("#tips").html(`<div class="alert alert-danger alert-dismissable">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>登入失敗: </strong> 密碼錯誤
</div>`);
break;
case 404:
$("#tips").html(`<div class="alert alert-danger alert-dismissable">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>登入失敗: </strong> 此帳號不存在
</div>`);
break;
}
}
});
});
});
</script>
</body>
</html>