封装Ajax(完整Ajax请求)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> new document </title>
<meta charset="utf-8"/>
<meta name="generator" content="kingwell" />
<meta name="author" content="" />
<meta name="keywords" content="" />
<meta name="description" content="" />
</head>
<body>
<div id="text"></div>
<script>
function Ajax(obj){
	var xml = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
	if (!xml){
		return;
	}
	var o = obj || {};
	var that = this;
	this.xml = xml;
	this.type = o.type || 'GET';
	this.asyn = o.asyn || false;
	this.url = o.url;
	this.data = o.data || null;
	this.setRequestHeader = o.setRequestHeader;
	this.timeOut = o.timeOut || 5000;
	this.onError = o.onError || function(){};
	this.onSuccess = o.onSuccess || function(){};
	this.onComplete = o.onComplete || function(){};
	if (!this.url){
		return;
	}
	this.xml.onreadystatechange = function(){
		if (this.readyState === 4){
			if (this.status === 200 || this.status === 403){
				that.onSuccess.call(this);
			}else{
				that.onError.call(this,this.status);
			}
		}
	}
	this.xml.open(this.type,this.url,this.asyn);
	for (var key in this.setRequestHeader){
		this.xml.setRequestHeader(key,this.setRequestHeader[key]);
	}
	this.xml.send(this.data);
	setTimeout(function(){
		that.xml.abort();
		that.onComplete(that);
	},this.timeOut);
	//alert(this.xml.getAllResponseHeaders());
	//alert(this.xml.getResponseHeader('Content-Type'));
}
new Ajax({
	type:'get',
	url : 'text.txt',
	timeOut : 1000,
	setRequestHeader :{
		'Content-Type' : 'text/html',
	},
	onSuccess : function(){
		//alert(this.responseText);
		//document.getElementById('text').innerHTML =this.responseText ;
		alert('success');
	},
	onError : function(code){
		//alert('error'+code);
	},
	onComplete : function(){
		//alert('完成了');
		console.log('完成了');
	}
});

</script>

</body>
</html>

相关推荐