HTML ペイジー(Boostrapに基づく)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.staticfile.net/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.net/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.net/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<title>Login Test</title>
</head>
<body>
<div class="container">
<h3>Welcome</h3>
<div class="alert" role="alert"></div>
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="user" class="col-sm-2 control-label">User</label>
<div class="col-sm-10">
<input type="text" class="user form-control" id = "user" >
</div>
</div>
<div class="form-group">
<label for="pwd" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="text" class="pwd form-control" id="pwd">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-default login-btn">Login</button>
</div>
</div>
</form>
</div>
<p class="my_p_1"></p>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="./js/login.js"></script>
</body>
</html>
Javascript(AJAXを使って)
const loginBtn = document.querySelector('.login-btn')
const myAlert = document.querySelector('.alert')
function alert (msg,success){
myAlert.classList.remove('d-none');
myAlert.innerText = msg
myAlert.classList.add('show')
myAlert.classList.add(success? 'alert-success':'alert-danger')
setTimeout(()=> {
myAlert.classList.add('d-none');
myAlert.innerText = ''
myAlert.classList.remove('show')
myAlert.classList.remove(success? 'alert-success':'alert-danger')
},1000)
}
loginBtn.addEventListener('click',function(){
event.preventDefault();
console.log("clicked")
const username = document.querySelector('.user').value
const password = document.querySelector('.pwd').value
console.log(username)
console.log(password)
const p = document.querySelector('.my_p_1')
axios({
url: 'http://hmajax.itheima.net/api/login',
method:'POST',
data:{
username,
password
}
}).then(result => {
console.log(result.data.message)
alert('Login Success!',1)
}).catch(error=>{
console.log(error.response.data.message)
alert('Login Failed!',0)
})
})