iT邦幫忙

2021 iThome 鐵人賽

DAY 21
0
Modern Web

JavaScript 筆記 2 版系列 第 21

JavaScript Day21 - AJAX(3)

axios

  • axios 是處理 AJAX 的套件,是透過 JavaScript Day19 - AJAX(1) 提到的 XMLHttpRequest 去發送請求,怕瀏覽器支援不支援 fetch 的話,可以考慮使用,作法跟 fetch 的概念蠻相似的
  • 官方網址:axios
  • 使用方法:上面的官方 GitHub 提到不少,假如採用 CDN 的方法如下方引用的例子
  • 基本語法:
    • axios.get(url, {}):依需求看是 getpost,以及 url 網址,若是像 post 有資料則放在 {}
    • .then(response):處理 response 的結果
    • .catch(error):處理 error 的結果

CDN 引用

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

基本的 GET

axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

POST 請求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

參考資料

JavaScript基本功修練:Day29 - axios基本語法與練習(GET、POST請求)
AJAX 完整解說系列:新增、更新、刪除(POST/PATCH/DELETE)
使用Axios你的API都怎麼管理?
axios中文文档|axios中文网

次回

感覺知道的都說完了,要想一下還可以再研究什麼


上一篇
JavaScript Day20 - AJAX(2)
下一篇
JavaScript Day22 - setTimeout、setInterval
系列文
JavaScript 筆記 2 版31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言