JavaScript 中ajax的封裝

<script>
    function ajax(options){
        options = options ||{};  //調用函數時如果options沒有指定,就給它賦值{},一個空的Object
        options.type=(options.type || "GET").toUpperCase();/// 請求格式GET、POST,默認爲GET
        options.dataType=options.dataType || "json";    //響應數據格式,默認json

        var params=formatParams(options.data);//options.data請求的數據

        var xhr;

        //考慮兼容性
        if(window.XMLHttpRequest){
            xhr=new XMLHttpRequest();
        }else if(window.ActiveObject){//兼容IE6以下版本
            xhr=new ActiveXobject('Microsoft.XMLHTTP');
        }

        //啓動併發送一個請求
        if(options.type=="GET"){
            xhr.open("GET",options.url+"?"+params,true);
            xhr.send(null);
        }else if(options.type=="POST"){
            xhr.open("post",options.url,true);

            //設置表單提交時的內容類型
            //Content-type數據請求的格式
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send(params);
        }

    //    設置有效時間
        setTimeout(function(){
            if(xhr.readySate!=4){
                xhr.abort();
            }
        },options.timeout)

    //    接收
    //     options.success成功之後的回調函數  options.error失敗後的回調函數
    //xhr.responseText,xhr.responseXML  獲得字符串形式的響應數據或者XML形式的響應數據
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                var status=xhr.status;
                if(status>=200&& status<300 || status==304){
                  options.success&&options.success(xhr.responseText,xhr.responseXML);
                }else{
                    options.error&&options.error(status);
                }
            }
        }
    }

    //格式化請求參數
    function formatParams(data){
        var arr=[];
        for(var name in data){
            arr.push(encodeURIComponent(name)+"="+encodeURIComponent(data[name]));
        }
        arr.push(("v="+Math.random()).replace(".",""));
        return arr.join("&");

    }
    //基本的使用實例
    ajax({
        url:"http://server-name/login",
        type:'post',
        data:{
            username:'username',
            password:'password'
        },
        dataType:'json',
        timeout:10000,
        contentType:"application/json",
        success:function(data){
      。。。。。。//服務器返回響應,根據響應結果,分析是否登錄成功
        },
        //異常處理
        error:function(e){
            console.log(e);
        }
    })
</script>

參考文章:

http://www.sohu.com/a/238246281_100109711

https://www.cnblogs.com/lanyueboyu/p/8793352.html

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