封装一个自己的ajax

/*
* @param type(必填)
* @param url(必填)
* @param data(必填)
* @parama callback(必填)
*/
function ajax(type,url,data,callback){
    var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")
    if(typeof data == "object"){
        var str = ""
        for(var key in data){
            str += `${key}=${data[key]}&`
        }
        data = str.slice(0,str.length - 1)
    }
    type = type.toUpperCase()
    if(type == "GET"){
        if(data){
            xhr.open("GET",`${url}?${data}`,true)            
        }else{
            xhr.open("GET",url,true)
        }
        xhr.send(null)
    }else if(type == "POST"){
        xhr.open('POST',url,true)
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        if(data){
            xhr.send(data)
        }else{
            xhr.send(null)
        }
    }else{
        return "error"
    }
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && xhr.status==200){
            const res = xhr.responseText;
            callback(res)
        }
    }
}

好啦

posted @ 2019-12-04 19:42  好多坨屎  阅读(658)  评论(0)    收藏  举报