1、创建ajax对象
var xhr = new XMLHttpRequest()
2、配置本次请求信息
xhr.open(请求方式,请求地址,是否异步)
3、注册请求完成事件
xhr.onload = function() {
console.log(xhr.responseText) //获取后端返回值
}
4、把请求发送出去
xhr.send()
在请求完成后执行函数中使用以下方式拿到返回内容:
JSON.parse(xhr.responseText)
注意,在post发送数据时,需要特殊说明传递参数的格式,这个后端会给,在发送数据前需要加上
xhr.setRequestHeader(‘content-type’,‘application/x-www-form-urlencoded’)
<style>
*{
margin: 0;
padding:0;
}
form {
width: 500px;
padding:20px;
margin: 50px auto;
border:3px solid pink;
display: flex;
flex-direction: column;
font-size:30px;
padding-top:50px;
position:relative;
}
form > span {
position: absolute;
left:50%;
top:5px;
transform:translateX(-50%);
width:100%;
text-align: center;
display:none;
}
style>
<body>
<script>
<form>
<span class="error">用户名或者密码错误</span>
<label>
用户名:<input class="username" type="text">
</label>
<label>
密码: <input class="passward" type="passward">
</label>
<button>登陆</button>
</form>
script>
<script>
var loginForm = document.querySelector('form')
var nameInp = document.querySelector('username')
var pwdInp = document.querySelector('.passward')
var errBox = document.querySelector('.error')
loginForm.onsubmit = function(e){
#阻止表单默认提交行为
e.preventDefault()
var name = nameInp.value
var pwd = pwdInp.value
if(!name || !pwd) return alert('请完整填写表单')
var xhr = new XMLHttpRequest()
xhr.open('POST','http://localhost:8080/users/login',true)
xhr.onload=function(){
var res = Json.parse(xhr.responseText)
console.log(res)
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='+passward)
}
script>
body>