ajax封装练习

ajax 封装练习

 ~ function () {
    class ajaxClass {
      //=>SEND AJAX
      init() {
        //=>THIS:EXAMPLE
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
          if (!/^[23]\d{2}$/.test(xhr.status)) return;
          if (xhr.readyState === 4) {
            let result = xhr.responseText;
            //=>DATA-TYPE
            try {
              switch (this.dataType.toUpperCase()) {
                case 'TEXT':
                case 'HTML':
                  break;
                case 'JSON':
                  result = JSON.parse(result);
                  break;
                case 'XML':
                  result = xhr.responseXML;
              }
            } catch (e) {

            }
            this.success(result);
          }
        };

        //=>DATA
        if (this.data !== null) {
          this.formatData();

          if (this.isGET) {
            this.url += this.querySymbol() + this.data;
            this.data = null;
          }
        }

        //=>CACHE
        this.isGET ? this.cacheFn() : null;

        xhr.open(this.method, this.url, this.async);
        xhr.send(this.data);
      }

      //=>CONVERT THE PASSED OBJECT DATA TO STRING DATA
      formatData() {
        //=>THIS:EXAMPLE
        if (Object.prototype.toString.call(this.data) === '[object Object]') {
          let obj = this.data,
            str = ``;
          for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
              str += `${key}=${obj[key]}  &`;
            }
          }
          str = str.replace(/&$/g, '');
          this.data = str;
        }
      }

      cacheFn() {
        //=>THIS:EXAMPLE
        !this.cache ? this.url += `${this.querySymbol()}_=${Math.random()}  ` : null;
      }

      querySymbol() {
        //=>THIS:EXAMPLE
        return this.url.indexOf('?') > -1 ? '&' : '?';
      }
    }

    //=>INIT   PARAMETERS
    window.ajax = function ({
      url = null,
      method = 'GET',
      type = null,
      data = null,
      dataType = 'JSON',
      cache = true,
      async = true,
      success = null
    } = {}) {
      let _this = new ajaxClass();
      ['url', 'method', 'data', 'dataType', 'cache', 'async', 'success'].forEach((item) => {
        if (item === 'method') {
          _this.method = type === null ? method : type;
          return;
        }
        if (item === 'success') {
          _this.success = typeof success === 'function' ? success : new Function();
          return;
        }
        _this[item] = eval(item);
      });
      _this.isGET = /^(GET|DELETE|HEAD)$/i.test(_this.method);
      _this.init();
      return _this;
    };
  }();

引入上面那一段js之后,在页面中直接调用
ajax({
	url:'',
	method:'POST',
	data:{name:'xxx',age:'xxx',sex:'xxx'},
	async:false //同步,默认是true(异步)
	success:function(res){
		// 成功回调
	}
	
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值