ajax 是什么
Asynchronous JavaScript + XML(异步 JavaScript 和 XML), 是由Microsoft公司发明
在前端中简单来讲主要是用于访问json数据,或者其它。
Ajax 详细代码
const xhr = new XMLHttpRequest()
xhr.open('GET', '/xxx')
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log('请求成功,得到内容为:' + xhr.responseText)
} else if (xhr.status >= 400) {
console.log('请求失败,状态码为:' + xhr.status)
}
}
}
xhr.send()
优缺点
优点 :
1. 可以请求任意内容
2. 不用刷新页面
缺点:
- 代码难记(一般都是封装后才使用)
- 不能跨域(对于老手来讲并不是缺点)