Ajax封装函数(GET请求方法)

1.创建xmlhttp = new XMLHttpRequest();对象。
2.xmlhttp.open(“GET”,url,true);声明发送方式为get,URL表示发送地址,如果是异步发送为true(推荐),同步为false。
3.xmlhttp.send(null);发送请求,send的参数一般为null。
4.xmlhttp.onreadystatechange通过onreadystatechange属性来检查提交状态。
5.xmlhttp.readyState ==4时表示提交成功,但是并不是最终的,还要通过检查状态码xmlhttp.status >=200 && xmlhttp.status <300 || xmlhttp.status == 304在这个范围就是成功了(状态码可以百度了解)。

//创建字符串函数
function objas(obj){
	
	obj.times = new Date.getTime();
	var arr = [];
	for(var key in obj){
		arr.push(encodeURIComponent(key)+"="+encodeURIComponent(obj[key]));
		//encodeURIComponent进行编码,防止出现中文
	}
	return arr.join("&");
}
//创建Ajax函数
function Ajax(url,obj,timeout,success,fail){
		var str = objas(obj);
		//解决兼容性问题
		var xmlhttp;
			if (window.XMLHttpRequest){
				// code for IE7+, Firefox, Chrome, Opera, Safari
			  	xmlhttp = new XMLHttpRequest();
			  }else{
				  // code for IE6, IE5
			    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			  }
		xmlhttp.open("GET",url+"?"+str,true);
		//发送请求
		xmlhttp.send(null);
		//检查请求状态
		xmlhttp.onreadystatechange = function(){
			//4表示请求成功,请求成功不代表最终成功
			if(xmlhttp.readyState ==4){
				clearInterval(timer);
				//判断HTTP的状态码
				if(xmlhttp.status >= 200 && xmlhttp.status <300 || 
				xmlhttp.status == 304){
					success(xmlhttp);//回调函数
				}else{
					fail(xmlhttp);//回调函数
			}
		}
	}
		//设置超时的时间
		if(timeout){
			timer = setInterval(function(){
				xmlhttp.abort();//中断请求
				clearInterval(timer);//关闭定时器
			},timeout);
		}
}

==觉得好就收藏吧,记得双击,谢谢!==
												__2019/02/04 美是初见__

你可能感兴趣的:(javascript)