還不會用ajax?教你封裝一個方便又好用的ajax

還不會用ajax?教你封裝一個方便又好用的ajax

1.準備工作 編寫方法

判斷是否爲對象
function isObject(arg){
    return (typeof arg === "object" && arg !== null && arg.constructor && arg.constructor === Object);
} 
根據請求方式修改date/url
function toUrlData(data,url,method){
    if(isObject(data)){
        var html = "";
        for(var attr in data){
            html += "&" + attr + "=" + data[attr];
        }
        html = html.slice(1);
        method = method || "";
        if(method.toUpperCase() === "POST"){
            return html;
        }
        url += "?" + html;
        return url;
    }
    return url;
}
合併對象
  function assign(){
        var target = arguments[0];
        for(var i = 1 ; i <arguments.length; i ++){
            for(var attr in arguments[i]){
                target[attr] = arguments[i][attr];
            }
        }
        return target;
    }

2.準備工作完成,開始封裝ajax

   function ajax(options){
   //首先定義一個默認的對象存儲默認的請求信息
        var _default = {
        //請求方式
            type:"GET",
            //請求路徑
            url:"",
            //請求數據 此處除了text 外可以json對象
            datatype:"text",
            //請求的數據
            data:null,
            //成功則執行
            success:function(){},
            //失敗則執行
            error:function(){},
            //完成則執行
            complete:function(){},
            //是否改變回調函數的this指向
            context:null
        }
        //首先利用剛纔封裝的合併對象方法 把的實參覆蓋原來定義的默認對象
        options = assign(_default,options);
        //把請求方式統一小寫/大寫 方便後面判斷
        options.type = options.type.toLowerCase();
		//判斷是否存在改變指針的對象 存在則利用bind改變指針指向
        if(isObject(options.context)){
            var calllist = ["success","error","complete"];
            calllist.forEach(function(item){
                options[item] = options[item].bind(options.context);
            })
        }
		//獲取xhr 此處用到了兼容性寫法
        var xhr = null;
        if(typeof XMLHttpRequest === "function"){
            xhr = new XMLHttpRequest();
        }else{
            xhr = new ActiveXObject("Microsoft.XMLHttp");
        }
        //判定請求方式 因爲get請求的url中附帶數據 post請求的date中攜帶數據 所以根據需求修改對應的數據
        if(options.type === "get"){
            options.url = toUrlData(options.data,options.url,options.type)
        }
        if(options.type === "post"){
            options.data = toUrlData(options.data,options.url,options.type)
        }
        //開放連接
        xhr.open(options.type,options.url,true);
        // 如果爲post要修改請求頭
        options.type === "post" ? xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded") : "";
        //傳送數據 get的話傳送null即可
        xhr.send(options.type === "post"?options.data:null);
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
            //當readyState爲4執行連接完成方法
                options.complete();
                //當status爲200-299執行連接成功方法
                if( /^2\d{2}/.test(xhr.status) ){
                    try{
                    //當用戶請求的對象爲json時 有可能會轉化錯誤 此處用拋異常 解決該問題
                        var res = options.datatype === "json"?JSON.parse(xhr.responseText):xhr.responseText;
                        options.success(res);
                    }catch(e){
                        options.error(e);
                    }
                }else{
                //否則執行連接失敗方法
                    options.error(xhr.status);
                }
            }
        }
    }

3.總結

1.聲明默認對象 用新的實參改變對象內容
2.獲取xhr
3.根據請求方式改變url 和 data
4.開放連接
5.post的話修改請求頭
6.發送數據
7.判定連接狀態 執行對應方法 一個ajax就完成啦
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章