AJAX封装(含jsonp)

function ajax(option){
    let {type,url,success,error,data,timeout}=option;
    type=type||"get";
    data=data||{};

    var str="";
    for(var i in data){
        str+=`${i}=${data[i]}&`;
    }
    if(type=='get' ||type=='jsonp'){
        var d=new Date();
        url=url+"?"+str+"__sS="+d.getTime();
    }

    if(type=='jsonp'){
        var sc=document.createElement('script');
        sc.src=url;
        document.body.appendChild(sc);
    
        window[data[data.columnName]]=function(res){
            success&&success(res);
            error=null;
        }
        setTimeout(()=>{
            error&&error("timeout");
            success=null;
        },timeout)
    }else{
        var xhr=new XMLHttpRequest();
        xhr.open(type,url,true);
        xhr.onreadystatechange=function(){
            if(xhr.readyState == 4 && xhr.status == 200){
                success(xhr.responseText);
            }else if(xhr.readyState == 4 && xhr.status != 200){
                error && error(xhr.status);
            }
        }

        if(type == "get"){
            xhr.send();
        }else if(type == "post"){
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xhr.send(str.slice(0,str.length-1));
        }
    }

}

你可能感兴趣的:(AJAX封装(含jsonp))