一、是什么
Async Javascript and XML(ajax) 即异步js和xml,一种创建交互式网页应用开发的技术,可以在不重新加载整个网页的情况下与服务器交换数据并更新部分网页。 原理:简单来说,通过XMLHttpRequest对象向服务器发送异步请求,从服务器获取数据,然后通过js操作dom更新网页。
二、实现过程
- 创建XMLHttpRequest对象
- 通过XMLHttpRequest对象的open方法建立与服务器的连接
- 通过XMLHttpRequest对象send方法将数据发送给服务器
- 通过XMLHttpRequest对象的onreadystatechange事件监听服务器端的通信状态
- 接收并处理服务端向客户端返回的数据结果
- 将处理结果更新到HTML页面
三、封装ajax
// 封装ajax
// 先来个ajax的例子
ajax({
type: 'post',
daType: 'json',
data: {},
url: 'http://www.baidu.com',
success: function (res, xml) {
console.log(res)
},
fail: function (res) {
console.log(res)
}
})
function ajax(options, params) {
// 1.创建XMLHttpRequest对象
const xhr = new XMLHttpRequest()
// 处理参数,此处省略
// 2.发送请求
if (options.type === 'get') {
xhr.open('GET', options.url + '?' + params, true)
} else if (options.type === 'post') {
xhr.open('POST', options.url)
xhr.send(params)
}
// 3.接收数据,并处理回调函数
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
let status = xhr.status
if (status >= 200 && status < 300) {
options.success && options.success(xhr.responseText, xhr.responseXML)
} else {
options.fail && options.fail(status)
}
}
}
}