JAVASCRIPT
VUE
REACT
NODE
ES6
TYPESCRIPT

Js手动封装http请求

2021. 05. 06    

JS手动封装HTTP请求,GET和POST

<script>
  function getXhr() {
    var xhr = null;
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest();
    } else {
      //ie8-
      xhr = new ActiveXObject("Microsoft.XMLHttp");
    }
    return xhr
  }
  //url url路径   type:请求方式    data:请求参数类型    dataType:返回的字符类型
  function ajax({ url, type, data, dataType }) {
    return new Promise(function (resolve, reject) {
      //1. 创建异步请求对象
      var xhr = getXhr();
      //简单获取xhr
      // var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHttp");
      //2.监听绑定
      xhr.onreadystatechange = function () {
        //状态4 并且状态码200  成功
        if (xhr.readyState == 4 && xhr.status == 200) {
          //返回接受字符串为json时,自动转化json串
          if (dataType !== undefined && dataType.toLowerCase() === 'json') {
            var res = JSON.parse(xhr.responseText)
          } else {
            var res = xhr.responseText
          }
          resolve(res);
        }
      }
      //get
      if (type.toLowerCase() === 'get' && data !== undefined) {
        url += "?" + data
      }
      //3.打开连接
      xhr.open(type, url, true)
      //post 修改请求头信息
      if (type.toLowerCase() === 'post') {
        //增加 设置请求头
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urllencoded");
      }
      //4.发送请求
      if (type.toLowerCase() === 'post' && data !== undefined) {
        xhr.send(data)
      } else {
        xhr.send(null)
      }

    })
  }
</script>
<script>
  // https://gank.io/api/v2/banners   get
  (function () {
    ajax({
      url: 'https://gank.io/api/v2/banners',
      type: 'get',
      dataType: 'json'
    }).then(function (res) {
      console.log(res)
    })
  }())
</script>