码迷,mamicode.com
首页 > Web开发 > 详细

ajax请求封装

时间:2019-01-29 23:12:06      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:设置   ready   ext   sharp   head   on()   turn   div   url   

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请求封装

标签:设置   ready   ext   sharp   head   on()   turn   div   url   

原文地址:https://www.cnblogs.com/425500828zjy/p/10336155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!