原理:通过 XMLHttpRequest 对象来向服务器发送异步请求,从服务器获取数据,然后用 JS 来操作 DOM 去更新页面
实现过程
1. 创建 Ajax 的核心对象 XMLHttpRequest 对象
- new XMLHttpRequest() 实例化对象
2. 通过 XMLHttpRequest 对象的 open() 方法与服务端建立连接
- new XMLHttpRequest().open(method:表示请求方式,url:服务器的地址)
3. 构建请求所需的数据内容,并通过 XMLHttpRequest 对象的 send() 方法发送给服务器端
- new XMLHttpRequest().send(body:发送的数据)
- 如果使用 get 请求发送数据,那么 send() 参数设置为 null (即send(null))
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",url) // url 指的是服务器地址
xhr.send(null)
xhr.onreadystatechange = function() {
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
// console.log(xhr.responseText)
let obj = JSON.parse(xhr.responseText)
console.log(obj)
obj.result.forEach(item =>{
var div = document.creatElement('div')
div.innerHTML = item.name
document.querySelector('body').appendChild(div)
})
} else if(chr.readyState >= 400){
console.log("错误信息" + xhr.status)
}
}
}
JS 中如何封装一个 ajax 请求?
请求方式,请求地址,请求参数,请求参数的类型
请求返回结果
function ajax(options) {
// 创建 XMLHttpRequest 对象
const xhr = new XMLHttpRequest()
// 初始化参数内容
options = options || {}
options.type = (options.type || 'GET').toUpperCase()
options.dataType = options.dataType || 'json'
const params = options.data
// 发送请求
if(options.type === 'GET'){
// 第三个参数 async:b布尔值,表示是否异步执行操作
xhr.open('GET', options.url + "?" + params,true)
xhr.send(null)
} else if(options.type === 'POST') {
xhr.open('POST',options.url,true)
xhr.send(params)
}
// 接收请求
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status >= 200 && xhr.status < 300) {
// responseText 字符串形式的响应数据
// responseXML XML 形式的响应数据
options.success(xhr, responseText, responseXML)
} else {
options.fail(`参数错误` + status)
}
}
}
}
ajax({
type:'get',
dataType: 'json',
data: {
limit:10
},
url: '',
success: function(text,xml){ // 请求成功之后的回调函数
console.log(JSON.parse(text))
},
fail: function(status) { //请求失败之后的回调函数
console.log(status)
}
})
function getParams(data) {
let arr = []
for(let key in data) {
arr.push(`${key}=${data[key]}`)
}console.log(arr)
}
getParams()