Js Ajax 复习

//get请求
function get(url,params,callback){
	// XMLHttpRquest核心方法
    var request = new XMLHttpRequest();
    //链接到url
    request.open("GET",url);
    //发送数据
    request.send(params);
    //忽略MimeType的解码方式
    request.overrideMimeType("text/plain","charset=utf-8")
    //监听请求
    request.onreadystatechange = function(){
    	// 执行状态 和 状态码
        if(request.readyState === 4 && request.status === 200){
        	//获取请求头字段
            var type = request.getResponseHeader('Content-Type');
            if(type.indexOf('xml')!=-1&&request.responseXML){
                callback(request.responseXML)
            }
            else if(type === "application/json"){
                callback(JSON.parse(request.responseText))
            }
            else{
                callback(request.responseText)
            }
        }
    }
}
//post请求
function postData(url,data){
    var request = new XMLHttpRequest();
    //设置为 json 类型
	request.setRequestHeader("Content-Type","application/json")
    request.open("POST",url);
    request.onreadystatechange = function(){
       if(request.readyState === 4 && request.status === 200){
           return new Promise((resolve,reject)=>{
               resolve(request)
           })
        }
    }
    //监听进度
    request.onprogress = function(e){
    	//剩余长度
        if(e.lengthComputable){
        //已经传输的数据 所有数据的大小
            console.log(e.loaded/e.total);
            
        }
    }
    request.send(JSON.parse(data));
}

你可能感兴趣的:(Js Ajax 复习)