AJAX全称(Async Javascript and XML)即异步的JavaScript和XML,是一种创建交互式网页应用的网页开发技术,可以在不重新加载整个网页的情况下,与服务器交换数据,并且更新部分网页
Ajax的原理简单来说通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据,然后用JavaScript来操作DOM而更新页面
实现Ajax异步交互需要服务器逻辑进行配合,需要完成以下步骤:
· 创建Ajax的核心对象XMLHttpRequest对象
· 通过XMLHttpRequest对象的open()方法与服务端建立连接
· 构建请求所需的数据内容,并通过XMLHttpRequest对象的send()方法发送给服务器端
· 通过XMLHttpRequest对象提供的onreadystatechange事件监听服务器端你的通信状态
· 接受并处理服务端向客户端响应的数据结果
· 将处理结果更新到HTML页面中
· 举个例子:
const request = new XMLHttpRequest()
request.onreadystatechange = function(e){
if(request.readyState === 4){ // 整个请求过程完毕
if(request.status >= 200 && request.status <= 300){
console.log(request.responseText) // 服务端返回的结果
}else if(request.status >=400){
console.log("错误信息:" + request.status)
}
}
}
request.open('POST','http://xxxx')
request.send()
· 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)
}
})