ajax封装

70 阅读1分钟
 // 封装 ajax 请求
  var xhr = (function(){
    var o = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject('Microsoft.XMLHTTP');
    if(!o){
        throw new Error('您的浏览器不支持异步发起HTTP请求')
    }
    // 将 ajax 传递的参数 拿到外面处理
    function  _doAjax(opt) {
        var opt = opt || {},
         url = opt.url,
         // 将 type 转为 大写
         type = (opt.type || 'GET').toUpperCase(),
         // 异步 or 同步
         async = opt.async || true,
         // GET 请求 data 为 null
         data = opt.data || null,
         error = opt.error || function () {
            
         },
         success = opt.success || function(){},
         complete = opt.complete || function(){};
          
        if(!url){
            throw new Error('请传入请求的URL地址')
        }
        o.open(type, url, async);
        // post 设置 请求头 传递数据 为 json 格式
        type === 'POST' && o.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        o.send(type === 'GET' ? null : (formatData(data)))
        console.log('>>>', formatData(data));
        o.onreadystatechange = function(){
            if(O.readyState === 4 && o.status === 200){
                success(JSON.parse(o.responseText))
                complete()
            }
            if(o.status === 404){
                error();
                complete()
            }
        }
    }
    function  formatData(obj) {
        var params = '';
        for (var i in obj){
            params += i + '=' +  obj[i] + '&';
        }
        return params.replace(/&$/, '')
    }
    return {
        ajax: function(opt){
            _doAjax(opt)
        },
        post: function(url, data, callback) {
            _doAjax({
                type: 'POST',
                url: url,
                data: data,
                success: callback
            })

        },
        get: function(url, callback) {
            _doAjax({
                type: 'GET',
                url: url,
                success: callback
            })
        }
    }
   })()

   xhr.ajax({
    url:'test',
    type: 'POST',
    data: {hh: 1234, we: 'abc'},
    success: function(data){
        console.log(data);
    }
   })