ajax请求封装

Posted 425500828zjy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax请求封装相关的知识,希望对你有一定的参考价值。

function ajax(method,url,data="",dataType="json"){
	return new Promise((resolve,reject)=>{
		//1 获取xhr
		var xhr= new XMLHttpRequest;
		//2 创建请求
		xhr.open(method,url,true);
		//3 设置请求头
		if(method=="post"){
			xhr.setRequestHeader(
				"Content-Type",
				"application/x-www-form-urlencoded";
			)}
		
		//4 设置回调
		xhr.onreadystatechange=function(){
			if(xhr.readyState==4)
				if(xhr.status==200){
					if(dataType=="json")
						resolve(JSON.parse(xhr.responseText));
					else
						resolve(xhr.responseText);
				else
					reject("请求出错:"+xhr.status);
			}		
		}
		
		//5 发送
		xhr.send(data);
		
			
		
		
})
}

  

以上是关于ajax请求封装的主要内容,如果未能解决你的问题,请参考以下文章