/**
 * 原生 ajax工具类
 * @author cls
 * @date 2021-01-30
 */

export const AjaxUtil = {
  get: function (option, callback) {
    // XMLHttpRequest对象用于在后台与服务器交换数据
    var me = this;
    var xhr = new XMLHttpRequest();
    xhr.open("GET", option.url, false);
    xhr.onreadystatechange = function () {
      me._onReadyStateChange(xhr, option, callback)
    };
    xhr.send();
  },
  // data应为'a=a1&b=b1'这种字符串格式，在jq里如果data为对象会自动将对象转成这种字符串格式
  post: function (option, callback) {
    var me = this;
    var xhr = new XMLHttpRequest();
    let async = (option.async == undefined ? true : option.async);

    option.contentType = option.contentType || "application/json"; //"application/x-www-form-urlencoded"
    xhr.open("POST", option.url, async);
    // 添加http头，发送信息至服务器时内容编码类型
    xhr.setRequestHeader("Content-Type", option.contentType);
    // "3d3fe30c-3d99-41e8-9aea-addd8528aa07"
    xhr.setRequestHeader("Authorization", "bearer " + "b9e6a365-c551-4551-b258-c56e3acd0eed");
    xhr.onreadystatechange = function () {
      me._onReadyStateChange(xhr, option, callback)
    };

    if (option.contentType == "application/json") {
      if (option.data) {
        xhr.send(JSON.stringify(option.data));
      } else {
        xhr.send();
      }
      return JSON.parse(xhr.responseText);
    } else {
      xhr.send(option.data);
      return xhr.responseText;
    }

  },
  // 监听请求状态变化
  _onReadyStateChange(xhr, option, callback) {
    if (xhr.readyState == 4) {
      if (xhr.status == 200 || xhr.status == 304) {
        try {
          callback && callback(JSON.parse(xhr.responseText));
        } catch (err) {
          callback && callback(xhr.responseText);
        }
      }
    }
  }
};