练手封装下ajax

练手封装下ajax,不是很好,正经应该是promise封装,再看看

       class HttpClient{
           constructor(){
               this.xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"); // 后面兼容IE5,6
           }
           get(url,params){
               const xhr = this.xhr
               if(typeof url === 'string'){
                 xhr.open('get',params?`${url}?${qs.stringify(params)}`:url,true);
                 xhr.send();
                 xhr.onreadystatechange = function(){
                     if(xhr.readyState === 4){
                         if(xhr.status >= 200 && xhr.status < 300){
                            return JSON.parse(xhr.responseText);
                         }
                     }
                 } 
               }else{
                throw new  TypeError(' get url error')
               }
              
           }
           post(url,params,header){
             const xhr = this.xhr
             if(typeof url !== 'string'){
                 throw new TypeError('post url error');
                 return
             }
             xhr.open('post',url,true); 
//header参数没有接,有需求得改一下
             xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 
             xhr.send(params?qs.stringify(params):'');
             xhr.onreadystatechange = function(){
                     if(xhr.readyState === 4){
                         if(xhr.status >= 200 && xhr.status < 300){
                             return JSON.parse(xhr.responseText);
                         }
                     }
                 } 
           }
       }

     const httpClient = new HttpClient();
     console.log(httpClient,'httpClient');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值