不满意JQuery Ajax的封装,自己动手干

锁定源头,自己封装Ajax

我们在使用JQuery的$.ajax封装的时候存在一个问题,就是在success下面无法实现对网络状态的多重不确定性的HTTP状态控制
下面我们自己来干一个:
注意!如果你使用 class ES6 module语法请将class置顶

XMLHttpRequest

/*@@@ **………………………………………………………………………………………………………………………………………
    @@@ ** …………………………… My Ajax  ………………………………
    @@@ **………………………………………………………………………………………………………………………………………
  */
<script>
   if($){$.ajax = ajax}else{window.$ = function(){};$.ajax = ajax;}
</script>
   function ajax(obj){
       var xhr = new XMLHttpRequest();
       xhr.open(obj.type, obj.url, true);
       if(obj.dataType)xhr.responseType=obj.dataType;
       if(obj.type!='GET'){
           xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
           xhr.send(obj.data)
       }else{
           xhr.send(null);
       }
       xhr.onreadystatechange = function(res){
           var response = xhr.response;
           if(xhr.readyState===4 && xhr.status===200){
               if(obj.dataType==='json'){
                   if(typeof xhr.response === 'string'){
                       response = JSON.parse(response);
                   }
               }
               obj.success(response);
           }else if(xhr.status!=200){
               obj.fail(xhr.status);
           }
       }
   }

调用:

$.ajax({
   url: 'http://dome.php',
   type: 'GET',
   success: function(res) {
            console.log(res)
    },
    fail: function(httpStatus) {
           switch(httpStatus) {
               case 500:  // doit
                     break;
          }
    }
})

JQuery也不是所有的都适合自己,根据场景需求,需要在JavaScript引擎APi定制

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容