AJAX 是现在开发网页必定要会的技能,其全名为 Asynchronous JavaScript and XML,可以仅向伺服器传送并取回需要的资料,因此伺服器和浏览器之间交换的资料大量减少,也让伺服器回应的速度更快,而实现的方式又有许多种,这边介绍几个方法与套件
XMLHttpRequest
XHR 是最原始的方法,目前大部分的套件都是基于此方法实作,但是有一些缺点
不符合关注点分离 ( Separation of Concerns )设定与使用上较为混乱容易造成 callback 地狱也因为以上缺点才会诞生出了其他的套件与方法
範例 - GET 方法
const xhr = new XMLHttpRequest();// 宣告一个 xhr 物件xhr.open('GET', 'https://uinames.com/api/', true);// 方法、API、同步与非同步 ( false 为同步,true 为非同步 )xhr.onload = () => console.log(xhr.response);// 成功则执行此函式xhr.onerror = err => console.log(err);// 失败则执行此函式xhr.send(null);// 送出资料
範例 - POST 方法
const xhr = new XMLHttpRequest();xhr.open('POST', 'https://uinames.com/api', true);// 方法改为 POSTxhr.setRequestHeader('Content-Type', 'application/json');// 设定 Headerxhr.onload = () => console.log(xhr);xhr.onerror = err => console.log(err);xhr.send({ name: 'Ares' });// 送出资料
Fetch
Fetch 是 ES6 的规範,使用上程式码相对简洁,但发展尚未成熟
优点
符合关注点分离 ( Separation of Concerns )写法较 XHR 精简使用 Promise 方法它是更为底层的 API,设定较弹性缺点
网路发生错误或中断时才会回传 reject,其余则回传 resolve预设不传送或接收任何 cookies不支援同步不支援请求进度显示不支援取消请求这边特别提一下,Fetch 返回的是一个 ReadableStream 物件,必须再将其转为可读懂的格式
arrayBuffer()formData()blob()json()text()範例 - GET 方法
fetch('https://uinames.com/api/')// API ( 预设为 GET ) .then(res => res.json()) // 转换 ReadableStream 物件 .then(data => console.log(data)) // 成功则执行此函式 .catch(err => console.log(err)); // 失败则执行此函式
範例 - POST 方法
fetch('https://uinames.com/api/', { method: 'POST', // 方法改为 POST headers: { 'Content-Type': 'application/json' }, // 设定 Header body: JSON.stringify(data), // 资料内容 credentials: 'include' // 若要使用 cookies 须加上此段设定}).then(res => res.json()) .then(data => console.log(data)) .catch(err => console.log(err));
jQuery
jQuery 很早就做出了自己的 AJAX 方法,虽然底层还是使用 XHR,但它将其改得更浅显易懂更好用,且新版本还支援了 Promise,可以说是非常好用
优点
支援 Promise API用法简单、功能多缺点
为了使用 AJAX 必须载入整个 jQuery範例 - GET 方法
$.ajax({ method: 'GET', // 方法 url: 'https://uinames.com/api/', // API async: true, // 同步与非同步 ( false 为同步,true 为非同步 ) data: null, // 送出的资料 datatype: 'json' // 回传的资料类型}).done(res => console.log(res)) // 成功则执行此函式 .fail(err => console.log(err)) // 失败则执行此函式 .always(res => console.log('完成')); // 不论失败或成功皆会执行此函式
範例 - POST 方法
$.ajax({ method: 'POST', // 方法改为 POST url: 'https://uinames.com/api/', async: true, data: { name: 'Ares' }, // 送出的资料 datatype: 'json'}).done(res => console.log(res)) .fail(err => console.log(err)) .always(res => console.log('完成'));
Axios
Axios 是一个轻量的 AJAX 套件,本质上亦是将 XHR 方法做封装,并使用 Promise 方法,对一个单纯用来做 AJAX 的套件几乎可以说是没有什么缺点
优点
支援 Promise API用法简单、功能多相当轻量自动转换 JSON客户端支援防止 CSRF範例 - GET 方法
axios.get('https://uinames.com/api/')// API .then(res => console.log(res.data)) // 成功则执行此函式 .catch(err => console.log(err)); // 失败则执行此函式
範例 - POST 方法
axios.post('https://uinames.com/api/',// 方法改为 POST { name: 'Ares' }, // 送出的资料 { headers: { 'Content-Type': 'application/json' } } // 各项设定).then(res => console.log(res.data)) // 成功则执行此函式 .catch(err => console.log(err)); // 失败则执行此函式
结语
现在前端各种框架盛行,jQuery 已不再是必须,其 AJAX 功能固然好用,但若只是单纯使用 AJAX 的话 jQuery 还是太大包,而 Axios 是目前最佳选择,轻量、设定简单、功能多,而 Fetch 目前尚未发展成熟,待之后发展亦有可能将其它套件取代,但看起来还需一段时间!