原理:通过XMLHttpRequest对象来向服务器发送异步请求,从服务器获取数据,然后用js来操作DOM去更新页面
实现过程:
1)创建ajax的核心对象,XMLHttpRequest对象
- new XMLHttpRequest()实例化对象
2)通过XMLHttpRequest对象的open()方法与服务端建立连接
- new XMLHttpRequest().open
- 两个参数:method:表示请求方式,url:服务器的地址
3)构建请求所需的数据内容,并通过XMLHttpRequest对象的send()方法发送给服务器端
- new XMLHttpRequest().send()
- 参数:body发送的数据
4)通过XMLHttpRequest对象提供的onreadystatechange事件监听服务端的通信状态
new XMLHttpRequest().onreadystatechange主要监听的属性时实例化对象readystate(五个状态)
- 0:open()未调用
- 1:send()未调用
- 2:send()已调用
- 3:响应体正在下载,responseText(接受服务端响应的结果)获取到部分数据
- 4:整个请求过程已经完毕
只要readystate属性值发生了改变,onreadystatechange被触发
5)接受并处理服务端向客户端响应的数据结果
6)将处理的结果更新到HTML中
const xhr=new XMLHttpRequest()
xhr.open('GET','http://localhost:3000/personalized?limit=10')
xhr.send(null)
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)//将JSON格式的数据转换为对象
}else if(xhr.status>=400){
console.log('错误信息'+xhr.status);
}
}
}