逻辑:
1. 我得在点击登录按钮的时候发送请求
=> 需要给 form 标签绑定一个 submit 事件
=> 注意: 在 事件内, 需要阻止默认行为
2. 获取到用户输入的内容
3. 表单验证
=> 非空验证
=> 正则验证
4. 把用户名和密码发送给后端
=> 使用 ajax 发送
=> 请求地址和方式, 看接口文档
5. 根据后端给出的响应, 来做对应的操作
const form = document.querySelector('form')
const nameInp = document.querySelector('.username')
const pwdInp = document.querySelector('.password')
// 1. 绑定事件
form.addEventListener('submit', e => {
// 处理事件对象兼容
e = e || window.event
// 阻止默认行为
try { e.preventDefault() } catch(err) { e.returnValue = false }
// 2. 获取到用户输入的内容
const name = nameInp.value
const pwd = pwdInp.value
// 3. 非空验证
if (!name || !pwd) return alert('请完整填写表单')
// 4. 发送 ajax 请求
const xhr = new XMLHttpRequest()
xhr.open('POST', 'http://localhost:8888/users/login')
xhr.onload = function () {
const res = JSON.parse(xhr.responseText)
console.log(res);
if (res.code === 0) {
alert(res.message)
return
}
// 跳转页面
window.location.href = 'https://www.jd.com'
}
// 因为是 post 请求, 并且携带了参数, 需要提前设置请求头
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
xhr.send(`username=${ name }&password=${ pwd }`)
})
<form>
<label>
用户名: <input class="username" type="text">
</label>
<br>
<label>
密码: <input class="password" type="text">
</label>
<button>登录</button>
</form>