﻿/*
Subj:ajax类
*/
var Ajaxpack = new Object();
Ajaxpack.READY_STATE_UNINITIALIZED = 0;
Ajaxpack.READY_STATE_LOADING = 1;
Ajaxpack.READY_STATE_LOADED = 2;
Ajaxpack.READY_STATE_INTERACTIVE = 3;
Ajaxpack.READY_STATE_COMPLETE=4;

Ajaxpack.Ajax = function(url,onload,onerror,method,params,contentType){
	this.req = null;
	this.onload = onload;
	this.onerror = (onerror) ? onerror : this.defaultError;
	this.loadXMLDoc(url,method,params,contentType);
}

Ajaxpack.Ajax.prototype.loadXMLDoc = function(url,method,params,contentType){
	if(!method) {
		method = 'GET';
	}
	if(!contentType && method=='POST') {
		contentType = 'application/x-www-form-urlencoded';
	}

	if(window.XMLHttpRequest) {
		this.req = new XMLHttpRequest();
	}
	else if(window.ActiveXObject) {
		try {
			this.req = new ActiveXObject("Msxml2.XMLHTTP"); 
		}
		catch (e){
			try {
				this.req = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	}

	if(this.req) {
		try{
			var loader = this;
			this.req.onreadystatechange = function(){
				Ajaxpack.Ajax.onReadyState.call(loader);	
			}
			this.req.open(method,url,true);
			if(contentType) {
				this.req.setRequestHeader('Content-Type',contentType);
			}
			this.req.send(params);
		}
		catch (e){
			this.onerror.call(this);
		}
	}
}

Ajaxpack.Ajax.onReadyState = function(){
	var req = this.req;
	var ready = req.readyState;
	if (ready==Ajaxpack.READY_STATE_COMPLETE){
		var httpStatus = req.status;
		if(httpStatus==200 || httpStatus==0) {
			this.onload.call(this);
		}
		else{
			this.onerror.call(this);
		}
	}
}

Ajaxpack.Ajax.prototype.defaultError = function(){
  alert("出现异常！");
  return true;
}

/*
instance,url,onload,onerror,method,params,contentType
*/
Ajaxpack.Ajax.exec = function(options){
	var ajaxInstance = options.instance;
	if(!ajaxInstance) {
		alert('运行Ajax之前，请先定义实例对象.');
		return false;
	}
	ajaxInstance = new Ajaxpack.Ajax(options.url,function(){
		var data = this.req.responseText;
		var json = eval("(" + data + ")");
		if(json.error) {
			this.onerror ? this.onerror(json.error) : alert(json.error);
			return false;
		}
		options.onload.call(this,json);
	},options.onerror,options.method,options.params,options.contentType);
	ajaxInstance = null;	
}


Ajaxpack.Ajax.txt = function(options){
	var ajaxInstance = options.instance;
	if(!ajaxInstance) {
		alert('运行Ajax之前，请先定义实例对象.');
		return false;
	}
	ajaxInstance = new Ajaxpack.Ajax(options.url,function(){
		var data = this.req.responseText;
		options.onload.call(this,data);
	},options.onerror,options.method,options.params,options.contentType);
	ajaxInstance = null;	
}
