Ajax

它的全称是:Asynchronous JavaScript And XML,翻译过来就是“异步的 Javascript 和 XML”。

const SERVER_URL = "/server";
let xhr = new XMLHttpRequest();
// 创建 Http 请求
xhr.open("GET", SERVER_URL, true);
// 设置状态监听函数
xhr.onreadystatechange = function() {
  if (xhr.readyState !== 4) return;
  // 当请求成功时
  if (xhr.status === 200 || xhr.status === 304) {
    console.log(xhr.responseText);
  } else {
    console.error(xhr.statusText);
  }
};
// 发送 Http 请求
xhr.send();
//使用Promise封装AJAX请求
const getJSON = function (url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, false);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onreadystatechange = function () {
      if (xhr.readyState !== 4) return;
      if (xhr.status === 200 || xhr.status === 304) {
        resolve(xhr.responseText);
      } else {
        reject(new Error(xhr.responseText));
      }
    };
    xhr.send();
  });
};

Fetch

<body>
  <script>
    function ajaxFetch(url) {
      fetch(url).then(res => res.json()).then(data => {
        console.info(data)
      })
    }
    ajaxFetch('https://smallpig.site/api/category/getCategory')
  </script>
</body>

Axios

面试题:Ajax、Fetch、Axios三者的区别-LMLPHP

 

04-14 01:14