原理:通过XMLHttpRequest对象来向服务器发送异步请求,从服务器获取数据,然后用js操作DOM去更新页面
实现过程:
--创建Ajax的核心对象,XMLHttpRequest对象
new XMLHttpRequest()实例化对象
--通过XMLHttpRequest对象的open()方法与服务器建立连接
new XMLHttpRequest().opne(method:表示请求方式,url:服务器地址)
new XMLHttpRequest().send(body:发送的数据)
如果使用get请求发送数据,send()参数设置为null
如果使用post请求发送数据,send()参数设置为JSON字符串,
--通过XMLHttpRequest对象提供的onreadstatechange事件监听服务器的通信状态
new XMLHttpRequest().onreadystatechange主要监听的属性是实例化对象中的readyState(五个状态)
0:open()未调用
1:send()未调用
2:send()已经调用,响应头和响应状态已经返回
3:响应体正在下载,responseText(接收服务器响应的结果)获取到部分数据,
4:整个请求过程已经完毕
只要readyState属性发生了改变,onreadyStatechange被触发
--接收并处理服务端向客户端响应的数据结果
--将处理结果更新到HTML页面中
<script>
// 创建实例对象
const xhr=new XMLHttpRequest();
// 建立连接
// get 请求
// xhr.open("GET","数据接口地址")
// post请求
xhr.open("POST","数据接口地址")
// post请求设置请求头
xhr.setRequestHeader("Conent-Type","application/x-www-form-urlencode")
// 发送请求
// get请求发送数据请求为null
xhr.send(null)
// post发送数据请求
xhr.send({"name":'勇士总冠军'})
// onreadstatechange事件监听服务器的通信状态
xhr.onreadystatechange=function(){
// 判断请求过程是否完成
if(xhr.readyState===4){
// 判断数据是否获取成功
if(xhr.status>=200&&xhr.status<300){
console.log(xhr.responseText);
// 拿到的数据是JSON格式,需要转换成对象
let obj=JSON.parse(xhr.responseText)
// 将拿到的数据,循环遍历后,更新到页面中
obj.result.forEach(item => {
var div=document.createElement('div')
div.innerHTML=item.name
document.querySelector('body').appendChild('div')
});
}else if(xhr.status>400){
console.log("错误信息"+xhr.status);
}
}
}
</script>