文章参考:JavaScript案例(六):前后端交互-登录案例_小张小张啊的博客-CSDN博客
一、需求分析
问题1: 什么时候进行发送请求?
点击登录按钮的时候,需要给 form 标签绑定一个表单提交事件。
问题2:需要拿到哪些信息?
需要拿到用户填写的用户名和密码。
问题3:需要如何发送给后端?
按照接口文档的规范进行发送。
问题4:请求完成以后,我们需要做些什么?
根据后端返回的信息,进行一些后续的操作。如果后端返回的是登录成功,那么我们进行页面跳转;如果后端返回的是登录失败,那么我们提示用户错误。
二、代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>案例:登录</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
background: #efefef;
background-size: 100% 100%;
background-repeat: no-repeat;
}
form {
background-color: #fbf9ff;
width: 350px;
padding: 20px;
margin: 180px auto;
border: 2px solid #2f11f1;
display: flex;
flex-direction: column;
font-size: 25px;
padding-top: 50px;
position: relative;
border-radius: 8px;
}
form>span {
position: absolute;
left: 50%;
top: 5px;
transform: translateX(-50%);
width: 100%;
text-align: center;
color: red;
display: none;
}
form>label {
height: 35px;
}
form>label>input {
font-size: 18px;
height: 25px;
padding-left: 10px;
}
button {
margin: 15px auto;
width: 80px;
height: 35px;
background-color: #c0bcff;
border-color: #8395fa;
border-radius: 5px;
}
</style>
</head>
<body>
<form>
<span class="error">用户名或者密码错误</span>
<label>
账号:<input class="username" type="text">
</label>
<label>
密码:<input class="password" type="password">
</label>
<button>登录</button>
</form>
<script>
//1.获取元素
var loginForm = document.querySelector('form')
var nameInp = document.querySelector('.username')
var pwdInp = document.querySelector('.password')
var errBox = document.querySelector('.error')
//1. 给form 绑定一个表单提交事件
loginForm.onsubmit = function(e) {
//注意:要阻止表单的默认提交行为
e.preventDefault()
//2. 拿到用户填写的用户名和密码
var name = nameInp.value
var pwd = pwdInp.value
//2-2. 验证用户名和密码
// if(!name || !pwd) return alert('请填写账号密码')
if (!name) return alert('请填写账号!')
if (!pwd) return alert('请填写密码!')
//3. 发送ajax请求
var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://localhost:8080/user/login', true)
xhr.onload = function() {
//返回json格式,需要解析
console.log(JSON.parse(xhr.responseText))
//进行条件判断
if (res.code === 0) {
//登录失败
errBox.style.display = 'block'
} else {
//登录成功
window.location.href = './home.html'
}
}
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
xhr.send('username=' + name + '&password=' + pwd)
console.log(name, pwd)
}
</script>
</body>
</html>
效果: