$.ajax封装

2018-12-10  本文已影响0人  lovinglili

思路

代码实现

$.ajax=function(options){
        var transp=window.ActiveXObject?new ActiveXObject():new XMLHttpRequest();
        switch(options.type){

            case "get":{
                transp.open("get",options.url,true);
                transp.onreadystatechange=function(){
                    if(transp.readyState==4){
                        if(transp.status==200||transp.status==304){
                            var msg=transp.responseText;
                            options.success(msg);//回调函数
                        }
                    }
                }
                transp.send();
                break;
            }
            case "post":{
                transp.open("post",options.url,true);
                transp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                transp.onreadystatechange=function(){
                    if(transp.readyState==4){
                        if(transp.status==200||transp.status==304){
                            var msg=transp.responseText;
                            options.success(msg);
                        }
                    }
                }
                var str="";
                for(var arr in options.data){
                    str+=arr+"="+options.data[arr]+"&";
                }
                transp.send(str.substring(0,str,length-1));
                break;
            }
            case "JSONP":{
                var script=document.createElement("script");
                var name="_cbk"+parseInt(Math.random()*1000)+new Date().getTime();
                script.src=options.url+"&"+options.cab+"="+name;
                window[name]=function(data){
                    options.success(data);
                    script.remove();
                    delete window[name];
                }
                document.body.appendChild(script);
                break;
            }
        }
}
上一篇下一篇

猜你喜欢

热点阅读