AJAX 包括以下几个步骤
一般实现:
const SERVER_URL = '/server'; let xhr = new XMLHttpRequest(); // 创建 Http 请求 第三个参数为async,指定请求是否为异步方式,默认为 true。 xhr.open('GET', SERVER_URL, true); // 设置请求头信息 xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); // 设置状态监听函数 xhr.onreadystatechange = function () { if (this.readyState !== 4) return; // 当请求成功时 if (this.status === 200) { handle(this.responseText); } else { console.error(this.statusText); } }; // 设置请求失败时的监听函数 xhr.onerror = function () { console.error(this.statusText); }; // 发送 Http 请求 xhr.send(null);
promise 封装实现:
function getJSON(url) { // 返回一个 promise 对象 return new Promise(function (resolve, reject) { let xhr = new XMLHttpRequest(); // 新建一个 http 请求, 第三个参数为async,指定请求是否为异步方式,默认为 true。 xhr.open('GET', url, true); // 设置状态的监听函数 xhr.onreadystatechange = function () { /*0: 请求未初始化 1: 服务器连接已建立 2: 请求已接收 3: 请求处理中 4: 请求已完成,且响应已就绪*/ if (this.readyState !== 4) return; // 当请求成功或失败时,改变 promise 的状态 /*200: "OK" 404: 未找到页面*/ if (this.status === 200) { resolve(this.responseText); } else { reject(new Error(this.statusText)); } }; // 设置响应的数据类型 xhr.responseType = 'json'; // 设置请求头信息 xhr.setRequestHeader('Accept', 'application/json'); // 发送 http 请求 xhr.send(null); }); }
本文作者:前端小毛
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!