AJAX -axios套件學習筆記

2022/09/30閱讀時間約 3 分鐘
如有需要可以不用浪費效能重新將整個頁面重新載入,可以使用非同步的JS,使用動態載入資料

非同步JS原生寫法:XMLHttpRequest、Fetch

XMLHttpRequest

初代寫法,程式碼較冗長,要送出請求,要新增一個XMLHttpRequest物件、開啟一個URL
function reqListener () {
  console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();

Fetch

Fetch相對XMLHttpRequest較新
fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

套件 axios

axios

可以使用cdn連結
發出請求後,會先跳過該函式,回傳後才會執行該函式
axios.get('/user/12345')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });
如果不清楚data是否回傳了,可以在內部放一個function,資料回傳後可以執行(印出)
let ary = [];
axios.get("https://hexschool.github.io/ajaxHomework/data.json")
   .then(function (response) {
    ary = response .data;
    renderData(); // 資料回傳後執行
});
function renderData(){
  console.log(ary);
}
console.log(ary); // 先執行 []
參考資料:
  1. https://developer.mozilla.org/zh-TW/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
  2. https://developer.mozilla.org/zh-TW/docs/Web/API/Fetch_API/Using_Fetch
  3. https://github.com/axios/axios
以上為資料整理,不完整之處請告知,謝謝
阿君啊
阿君啊
正在往前端工程師的路上邁進~喜歡學習新知、小技巧幫助成為更好的自己!
留言0
查看全部
發表第一個留言支持創作者!