$.ajax封裝

思路

  • /ajax的get方式
    1.type:"get"
    2.url 寫在open函數(shù)里面,包含數(shù)據(jù)
    3.回調(diào)函數(shù),將處理得到的數(shù)據(jù)function(data){操作},
    /

  • *ajax的post方式 數(shù)據(jù)不能放在地址欄里面,所以要有data屬性,放在send函數(shù)里面發(fā)送
    1.type:"post"
    2.url
    3.data{
    diyigeshuju:
    diergeshuju:
    }
    4,回調(diào)函數(shù)
    */

  • /ajax的跨域操作,JSONP。通過sccript標(biāo)簽發(fā)送api請求,然后調(diào)用回調(diào)函數(shù),得到數(shù)據(jù)
    1.type:"JSONP
    2.url
    3cab:(地址欄里面的key )
    4,回調(diào)函數(shù)
    /

代碼實現(xiàn)

$.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);//回調(diào)函數(shù)
                        }
                    }
                }
                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;
            }
        }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容