美文网首页
$.ajax封装

$.ajax封装

作者: lovinglili | 来源:发表于2018-12-10 11:59 被阅读0次

思路

  • /ajax的get方式
    1.type:"get"
    2.url 写在open函数里面,包含数据
    3.回调函数,将处理得到的数据function(data){操作},
    /

  • *ajax的post方式 数据不能放在地址栏里面,所以要有data属性,放在send函数里面发送
    1.type:"post"
    2.url
    3.data{
    diyigeshuju:
    diergeshuju:
    }
    4,回调函数
    */

  • /ajax的跨域操作,JSONP。通过sccript标签发送api请求,然后调用回调函数,得到数据
    1.type:"JSONP
    2.url
    3cab:(地址栏里面的key )
    4,回调函数
    /

代码实现

$.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;
            }
        }
}

相关文章

网友评论

      本文标题:$.ajax封装

      本文链接:https://www.haomeiwen.com/subject/jajrhqtx.html