﻿// XMLHttpRequest对象封装类
function HttpClient(){}
HttpClient.prototype={

	isAsync:true,//是否是异步请求 true:异步请求false:同步请求
	xmlhttp:false,//XMLHttpRequest对象
	callback:false,//回调函数
	
	//调用XMLHttpRequest对象的send方法是执行
	onSend:function(){
		
	},
	//XMLHttpRequest对象的readyState值为4时将调用的内容
	onLoad:function(){
	
	},
	//出错调用的内容
	onError:function(error){
		alert(error);
	},
	//初始化XMLHttpRequest
	init:function(){
		try{
			this.xmlhttp=new XMLHttpRequest();	
		}catch(e){    //如果不能建立则创建IEActiveXObject对象
			try{			
			    this.xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
			}catch(e){
			    this.onError("无法创建XMLHttpRequest对象！");
			}
		}               
	},
	//发起Get请求
	//参数：url请求的页面路径
	makeGetRequest:function(url){
	    if(!this.xmlhttp){
			this.init();
		}
		this.xmlhttp.open("GET",url,this.isAsync);
		this.xmlhttp.setRequestHeader("If-Modified-Since", "Sat,1 Jan 2000 00:00:00 GMT");
		var self=this;
		this.xmlhttp.onreadystatechange=function(){
			self._readyStateChangeCallback();	
		}
		this.xmlhttp.send(null);
		if(!this.isAsync){
			return this.xmlhttp.responseText;
		}
	},
	//发起Post请求
	//参数：url请求的页面路径,payload Post请求的数据(发送到服务器)
	makePostRequest:function(url,payload){
	    if(!this.xmlhttp){
			this.init();
		}
		this.xmlhttp.open("POST",url,this.isAsync);
		this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		this.xmlhttp.setRequestHeader("If-Modified-Since", "Sat,1 Jan 0001 00:00:00 GMT"); //时间必须小于当前时间才会调用_readyStateChangeCallback
		var self=this;
		this.xmlhttp.onreadystatechange=function(){
			self._readyStateChangeCallback();	
		}
		this.xmlhttp.send(payload);
		if(!this.isAsync){
			return this.xmlhttp.responseText;
		}
	},
	//当XMLHttpRequest对象的readyState的值发生变化时，将调用的内容
	_readyStateChangeCallback:function(){
		switch(this.xmlhttp.readyState){
			case 2://已调用send方法，但状态和报头还不可用
				this.onSend();
				break;
			case 4://所有数据都已收到
				this.onLoad();
				if(this.xmlhttp.status==200 || this.xmlhttp.status==304){
					this.callback(this.xmlhttp.responseText);//请求成功，调用的回调内容
				}else{
					this.onError('Http请求错误: '+this.xmlhttp.status+' '+this.xmlhttp.statusText);	
				} 
				break;
		}
	}
}

