ajax和axios的区别

153 阅读1分钟

(作者笔记自用)

首先要知道的是,ajax指的是XMLHttpRequest(XHR),它是最早的向后端发送网络请求的技术,是原生JavaScript中用于网页局部数据刷新的技术,可能会出现回调地狱,以下是原生JavaScript中发起ajax请求的代码:

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     console.log("send true);
    }
  };
  xhttp.open("GET", "文件位置", true);
  xhttp.send();

然后是axios,我最先了解到axios是因为vue的作者尤雨溪,他推荐使用vue的开发者使用axios来替换jQuery ajax,简单地说axios就是对ajax的封装,并且他还是promise实现的版本,更加的符合最新的ES规范,以下是axios发起ajax请求的代码:

  axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

补充一个fetch()函数:

fetch('/some/url', {
         method: 'get',
     })
         .then(function (response) {})
         .catch(function (err) {});