$.ajax實現原理(封裝ajax)

/*<script>
    ajax({
        url:"data/data.json",
        method:"get",
        data:{name:"zf"},
        dataType:"json",
        cache:false,
        async:false,
        success:function (res) {
            console.log(res);
        }
    })
</script>*/
//ajax.js
/*
ajax({
   url:"請求路徑",
   type:"請求方式 type和method 一樣使用",
   dataType:"返回數據的類型 默認是text",
   cache:"是否走緩存",
   data:"請求的參數,如果是get請求,會將這裏的內容拼接到url",
   async:是否異步,
   success:成功的回調,
   error:失敗的時候的回調,
   complete:不管成功失敗都會觸發的函數
})

支持的參數
url,
method/type,
data,
dataType,
async,
cache,
success
*/

~function () {
    class Ajax{
        init(){
            let  xhr=new XMLHttpRequest();
            xhr.onreadystatechange= () =>{
                if(!/^[23]\d{2}$/i.test(xhr.status))return;
                if(xhr.readyState==4){
                    let result=xhr.responseText;
                    //對參數dataType
                    try {
                        switch (this.dataType.toUpperCase()){
                            case "TEXT":
                                break;
                            case "HTML":
                                break;
                            case "JSON":
                                result=JSON.parse(result);
                                break;
                            case "XML":
                                result=xhr.responseXML;
                                break;
                        }
                    }catch (e){
                        console.log(e);
                    }
                    this.success(result);
                }
            };
            //處理data
            if(this.data!==null){
                this.query();
                if(this.isGet){
                    //get請求需要將數據data拼接到url上
                    this.url+=this.queryBefore()+this.data;
                    //this.data沒有用了就清空了
                    this.data=null;
                }
            }
            //cache處理 只有get請求才有必要處理緩存
            this.isGet?this.cacheFn():null;
            xhr.open(this.method,this.url,this.async);

            xhr.send(this.data);
        }
        query(){
            //判斷data必須是一個對象的時候去講其變成字符串
            if(this.data&&this.data.toString()=="[object Object]"){
                let str=``;
                for (let key in this.data){
                    if(this.data.hasOwnProperty(key)){
                        str+=`${key}=${this.data[key]}&`;
                    }
                }
                //後面多一個&符號
                str=str.replace(/&$/g,"");
                this.data=str;
            }
        }
        queryBefore(){
            //判斷url有沒有?
            return this.url.includes("?")?"&":"?";
        }
        cacheFn(){
            //判斷this.cache是true還是false 只有false時候才處理緩存,加一個時間戳
            !this.cache?this.url+=`${this.queryBefore()}_t=${(new Date).getTime()}`:null;
        }
    }
    window.ajax=function ({
                              url=null,
                              method="GET",
                              type=null,
                              data=null,
                              dataType="JSON",
                              async=true,
                              cache=true,
                              success=null,
                          } = {}) {
        let _this=new Ajax();
        ["url","method","data","dataType","async","cache","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.isGet=/^GET|DELETE|HEAD$/i.test(_this.method);
            _this[item]=eval(item);
        });
        _this.init();
        return _this;
    }
}();


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章