Ajax(8) => 封装自己的Ajax

9.封装Ajax

参照jquery的单例模式

// 自己封装ajax
~(function () {
  function AJAX(option) {
    return new AJAX.prototype.init(option);
  };
  AJAX.prototype = {
    constructor: AJAX,
    sendAjax: function () { // 发送ajax请求
      this.handelCache();
      this.handleData();
      let {
        url,
        method,
        async,
        data,
        success,
        error
      } = this
      let xhr = new XMLHttpRequest();
      xhr.open(method, url, async);
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (!/^(2|3)\d{2}$/.test(xhr.status)) {
            error && error(xhr.statusText, xhr)
          } else {
            let result = this.handelDataType(xhr)
            success && success(result, xhr)
          }
        }
      }
      xhr.send(data)
    },
    handelDataType: function (xhr) { // 格式化服务器返回的数据格式
      let dataType = this.dataType.toLocaleUpperCase();
      let result = xhr.responseText;
      switch (dataType) {
        case "TEXT": {
          break
        }
        case "JSON": {
          result = JSON.parse(result);
          break
        }
        case "XML": {
          result = xhr.responseXML
        }
      }
      return result
    },
    handelCache: function () { // 处理相同url的get请求会产生缓存的问题,默认有缓存,cache=false时没有
      let {
        url,
        method,
        cache
      } = this;
      if (/^GET$/i.test(method) && cache.toLocaleLowerCase() === 'false') {
        this.toCheck('?') ? url += `&_=${+new Date()}` : url += `?_=${+new Date()}`;
        this.url = url;
      }
    },
    handleData: function () { // 处理url参数,根据请求方式决定
      let {
        method,
        data
      } = this;
      if (!data) {
        this.data = null
      }; // data参数没传,可能在url里,所以是get请求,send的参数设置为null
      if (data != null && typeof data === 'object') { // 如果data是object,把他转换成x-www-form-urlencoded格式,如果传递是json格式,请求头得设置
        let str = ``;
        for (let k in data) {
          if (data.hasOwnProperty(k)) {
            str += `${k}=${data[k]}&`
          }
        }
        data = str.length > 0 ? str = str.slice(0, -1) : str
        if (/^(GET|DELETE|HEAD|TRACE|OPTIONS)$/i.test(method)) {
          this.url += `${this.toCheck('?') ? '&' + data : '?'+data}`;
          this.data = null
        } else {
          this.data = data
        }
      }
    },
    toCheck: function (what) { // 检查url是存在?, 存在true,反之false
      return this.url.indexOf(what) !== -1 ? true : false
    },
  }
  AJAX.prototype.init = function (option = {}) {
    let {
      url,
      method = "GET",
      async = "true",
      data = null, // url参数
      dataType = 'JSON', // 服务端获取数据后对其数据格式的处理
      cache = "true", // 默认get请求产生缓存
      success,
      error
    } = option;
    ['url', 'method', 'async', 'data', 'dataType', 'cache', 'success', 'error'].forEach(item =>this[item] = eval(item));
    this.sendAjax()
  }
  AJAX.prototype.init.prototype = AJAX.prototype
  window.ajax = AJAX;
})(window)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值