原生
<script> // const SERVER_URL = '/server' let xhr = new XMLHttpRequest() //创建http请求 xhr.open('GET', url, true) //设置状态监听函数 xhr.onreadystatechange = function () { if (this.readyState === !4) return if (this.status === 200) { handle(this.response) } else { console.error(this.statusText) } } //设置请求失败监听函数 xhr.onerror = function () { console.error(this.statusText) } //设置请求头信息 xhr.responseType="json" xhr.setRequestHeader('Accept','application/json') //发送HTTP请求 xhr.send(null) </script>
promise封装ajax
<script> function getJSON(url) { //创建promise对象 let promise = new Promise(function (resolve, reject) { let xhr = new XMLHttpRequest() //创建http请求 xhr.open('GET', url, true) //设置状态监听函数 xhr.onreadystatechange = function () { if (this.readyState === !4) return // 请求成功或失败改变promise状态 if (this.status === 200) { resolve(this.response) } else { reject(new Error(this.statusText)) } } //设置请求失败监听函数 xhr.onerror = function () { reject(new Error(this.statusText)) } //设置请求失败监听函数 xhr.onerror = function () { console.error(this.statusText) } //设置响应类型 xhr.responseType = 'json' //设置请求头信息 xhr.setRequestHeader('Accept', 'application/json') //发送HTTP请求 xhr.send(null) }) return promise } </script>
Axios
Axios 是一种基于 Promise 封装的 HTTP 客户端,其特点如下:
浏览器端发起 XMLHttpRequests 请求
node 端发起 http 请求
支持 Promise API
监听请求和返回
对请求和返回进行转化
取消请求
自动转换 json 数据
客户端支持抵御 XSRF 攻击
Fetch
fetch 号称是 AJAX 的替代品,是在 ES6 出现的,使用了 ES6 中的 promise 对象。
Fetch 是基于 promise 设计的。Fetch 的代码结构比 19 起 ajax 简单多。
fetch 不是 ajax 的进一步封装,而是原生 js,没有 使用 XMLHttpRequest 对象。
fetch 的优点:
语法简洁,更加语义化 基于标准 Promise 实现,支持 async/await 更加底层,提供的 API 丰富(request, response) 脱离了 XHR,是 ES 规范里新的实现方式 fetch 的缺点: fetch 只对网络请求报错,对 400,500 都当做成功的请求,服务器 返回 400,500 错误码时并不会 reject,只有网络错误这些导致请 求不能完成时,fetch 才会被 reject。 fetch 默 认 不 会 带 cookie , 需 要 添 加 配 置 项 : fetch(url, {credentials: 'include'}) fetch 不 支 持 abort , 不 支 持 超 时 控 制 , 使 用 setTimeout 及 Promise.reject 的实现的超时控制并不能阻止请求过程继续在后台 运行,造成了流量的浪费 fetch 没有办法原生监测请求的进度,而 XHR 可以;