(三) 原生JavaScript使用Ajax的步骤(Router.js中有get/post接口)
一、定义一个ajax函数
const ajax = function () {}
二、获取节点值(Ajax函数中)
let username = document.getElementsByName("uname")[0].value;
let password = document.getElementsByName("upwd")[0].value;
三、在事件处理程序中创建XMLHttpRequest对象(Ajax函数中)
//声明一个常量xhr,默认为空
let xhr = null;
//兼容性判断:判断是否有XMLHttpRequest
if (window.XMLHttpRequest != undefined) {
//赋值给xhr:创建一个异步请求对象
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
四、打开一个链接(Ajax函数中)
1.定义一个url
(1)Get方法(模板字符串)
let url = `/api/login?uname=${username}&upwd=${password}`
(2)Post方法(单独的一个接口)
let url = '/api/login'
2.打开链接
语法:xhr.open(type,url,同步(false)/异步(true))
(1)Get方法
xhr.open('get', url, true)
(2)Post方法
A.打开链接
xhr.open('post', url, true)
B.设置请求头!!!
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded")
五、发送请求(Ajax函数中)
1.Get方法
xhr.send()
2.Post方法
xhr.send(`uname=${username}&upwd=${password}`)
六、配置ajax什么时候处理后台返回的数据,如何处理数据
xhr.onreadystatechange = function () {
console.log(xhr.status, "==========", xhr.readyState);
//4.1判断readyState状态码和httpp状态码
if (xhr.status === 200 && xhr.readyState === 4) {
//4.2从xhr.responseText获取后台返回的文本数据//字符串
//console.log(xhr.responseText);
//4.3转换为json格式
let resData = JSON.parse(xhr.responseText);
//4.4code==0登录成功
console.log(resData);
if (resData.code === 0) {
alert('登录成功')
sessionStorage.setItem('userinfo', JSON.stringify(resData.data))
location.href = "/html/main.html"
} else {
alert("登录失败")
}
}
}
注:
(1)Ajax: readyState状态码:
状态码 | 状态 |
---|---|
0 | ajax对象创建完毕,打开链接 |
1 | 数据发送之前 |
2 | 原始数据开始接收 |
3 | 解析数据 |
4 | 完成 |
(2)status http的状态码
状态码(开头数字) | 状态 |
---|---|
2 | 成功 |
3/4 | 都可认为是前端的问题导致 |
5/6 | 可认为是后台问题导致 |
详情见:http状态码百度百科
七、调用ajax函数
document.getElementById('btnLogin').onclick = ajax;//不带括号
注: 不带括号