Ajax的工作原理
Ajax工作就是在用户和服务器之间加一个中间层,使用户操作与服务器响应异步化。(异步的js和XML是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。)
组成:js,css,DOM,XMLHttpRequest对象
- Ajax提供与服务器异步通信的能力,可在web页面触发js事件中向服务器发出异步请求,如执行更新或查询数据库。
- Ajax的核心是js对象XMLHttpRequest,改对象在IE5中首次引入,使用户通过js向服务器提出请求并处理相应,不阻塞用户。
- 当web服务器的相应返回时,使用js回调函数和CSS相应的更新页面的局部页面,而不是刷新整个页面。
- 在页面与服务器交互的过程中不中断用户操作,用户甚至察觉不到浏览器正在与服务器进行通信。
XMLHttpRequest 对象
用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
1. open(‘method’,‘url’) 建立服务器的调用 ,method:请求的类型;GET 或 POST ,url:文件在服务器上的位置。
2.send(content) 向服务器发送数据 ,content:仅用于 POST 请求。
XMLHttpRequest的属性:
Onreadystatechange* 请求状态发生改变时,指定事件处理函数
readyState 请求响应过程中的状态码
responseText 服务器端的相应信息
status 服务器端响应的状态码
XMLHttpRequest对象的5个步骤
- 建立对象
- 注册回调函数
- 使用open方法设置和服务器端交互的基本信息。
- 发送数据开始和服务器端交互
- 在回调函数中判断交互是否结束,响应是否结束,响应是否正确,并根据从服务器返回的数据进行更新页面。
通过上面对XMLHttpRequest对象的了解,下面来封装一个简单的ajax请求
//封装一个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') {
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) {
let status = xhr.status
if (status >= 200 && status < 300) {
options.success && options.success(xhr.responseText, xhr.responseXML)
} else {
options.fail && options.fail(status)
}
}
}
}
使用
ajax({
type: 'post',
dataType: 'json',
data: {},
url: 'https://xxxx',
success: function(text,xml){//请求成功后的回调函数
console.log(text)
},
fail: function(status){请求失败后的回调函数
console.log(status)
}
})