﻿/**
 * XMLHttpRequest Object Pool
 *
 * @author    legend <legendsky@hotmail.com>
 * @link      http://www.ugia.cn/?p=85
 * @Copyright www.ugia.cn
 */

/*几个建议：
1、“对象池”的管理功能需要加强，比如池的容量。
2、“对象池”的内存回收需要加强，比如使用完毕的对象释放内存。
3、请求最好序列一下，以控制由于服务器延时或网络延时导致的先请求的后得到结果。
4、超时处理。
*/
var XMLHttp = {
	 request: function(url, method, proc, error, data) {
	 	this.requestEx(url,method,proc,error,data,true,null,null);
	 },
	 srequest: function(url, method, proc, error, data) {
	 	this.requestEx(url,method,proc,error,data,false,null,null);
	 },

    // 发送请求(地址，方法[post,get,head]，回调函数，错误处理函数，数据，异步，编码，字符集)
    requestEx: function (url, method, proc, error, data, asyn, encode, charset) {
        var xhr = this._getInstance();
		if(xhr == null) {
			alert("请求初始化失败！请稍后再试。");
			return;
		}
		if(!method) method = "GET";
		if(!asyn) method = true;
		if(!proc) proc = this.defaultProc;
		if(!error) error = this.defaultError;
		// 加随机数防止缓存
		url += (((url.indexOf("?")>0)?"&":"?")+"randnum=" + Math.random());
		// url += (((url.indexOf("?")>0)?"&":"?")+"timestamp=" + new Date().getTime());
		/*
		if (url.indexOf("?") > 0) // url += "&randnum=" + Math.random();
		url += "&timeStamp=" + new Date().getTime();
		else // url += "?randnum=" + Math.random();
		url += "?timeStamp=" + new Date().getTime();
		*/
		try {
			xhr.open(method, url, asyn);
			// 设定请求编码方式
			if(encode) {
				var ct = (charset? encode+"; charset="+charset:encode);
				//xhr.setRequestHeader('Content-Type', ct);
			}
	xhr.setRequestHeader('Content-Type', encode+"; charset=gb2312");
			xhr.onreadystatechange = function () {
				if (xhr.readyState == 4 )
					if(xhr.status == 200 || xhr.status == 304)
						proc.proc(xhr, proc);
					else
						error(null,xhr);
			};
//alert(data);
			xhr.send(data);
		} catch(e) { error(e, xhr); }
	},
	// 用在弹出窗口被关闭窗口时
    cancelAll : function() {
        var _createObj = this._createObj;
        this._createObj = function() {
            return null;
        }
        for (var i=0; i < this._objPool.length; ++i) {
            this._objPool[i].abort();
        }
        this._createObj = _createObj;
    },

	ENC_FORM: "application/x-www-form-urlencoded",
	// 'application/x-www-form-urlencoded; charset=UTF-8'

	defaultProc: {
		proc: function(xhr, obj) { alert(xhr.responseText); }
	},

	defaultError: function(e, xhr) {
		var desp = ""
		if(e)
			desp += ("错误名称：" + e.name + "\r\n" +
				"错误编号：" + e.number + "\r\n" +
				"错误信息：" + e.message + "\r\n" +
				"错误描述：" + e.description);
		if(xhr && xhr.readyState)
			desp += ("\r\n" + "请求状态码：" + xhr.status +
					"\r\n" + "请求状态描述：" + xhr.statusText);
		//alert(desp);
	},

    _objPool: [],

    _getInstance: function () {
		var op = this._objPool;
        for (var i = 0; i < op.length; i ++) {
            if (op[i].readyState == 0 || op[i].readyState == 4)
                return op[i];
        }
        // IE5中不支持push方法
        op[op.length] = this._createObj();
        return op[op.length - 1];
    },

    _createObj: function () {
		var xhr = null;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
			xhr.overrideMimeType("text/xml");
		}
        else {
            var MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0',
						'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
            for(var n = 0; n < MSXML.length; n ++) {
                try {
                    xhr = new ActiveXObject(MSXML[n]);
                    break;
                } catch(e) { }
            }
         }
        // mozilla某些版本没有readyState属性
        if (xhr && xhr.readyState == null) {
            xhr.readyState = 0;
            xhr.addEventListener("load", function () {
                    xhr.readyState = 4;
                    if (typeof xhr.onreadystatechange == "function")
                        xhr.onreadystatechange();
                },  false);
        }
        return xhr;
    }
};



