即Asynchronous(异步的) JavaScript And XML ,使用XM(XMLHttpRequest)与服务器通信
- 如何使用?
简易版
const xhr = new XMLHttpRequest() //创建请求
xhr.open('GET', '/xxx') //初始化请求
xhr.onerror = () => { //监听请求
console.log('请求失败,失败原因是:' + xhr.status)
}
xhr.onload = () => {
console.log('请求成功,得到内容是:' + xhr.response)
}
xhr.send() //发送请求
详细版
const xhr = new XMLHttpRequest() //创建请求
xhr.open('GET', '/xxx') //初始化请求,GET为请求方法,'/xxx'为请求路径
xhr.onreadystatechange = () => { //监听请求
if (xhr.readyState === 4) { //4代表请求已完成并且响应已准备好
if (xhr.status >= 200 && xhr.status < 300) { //状态码,200-300之间代表请求成功
console.log('请求成功,得到内容为:' + xhr.responseText)
} else if (xhr.status >= 400) {
console.log('请求失败,状态码为:' + xhr.status)
}
}
}
xhr.send() //发送请求
- AJAX的优缺点
优点:1.可以请求任意内容 2.不用刷新页面
缺点:1.代码难记,使用别人的封装(axios) 2.不能跨域
一般用于在不重新加载页面的情况下发送请求给服务器,接受并使用从服务器发来的数据