﻿
function Ajax(){
    this._create = function() {
        var _p;
        try {
            _p = new XMLHttpRequest();
        } catch (e) {
            var r = new Array("MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP");
            for (var i = 0; i < r.length && !_p; i++) {
                try {
                    _p = new ActiveXObject(r[i]);
                    if (_p) break;
                } catch (e) { }
            }
        }
        if (!_p) {
            alert('Fail to init Ajax.');
        } else {
            return _p;
        }
    }
    
    this.Request = function(parameters){
        var parm = parameters.data || null;
        var method = parameters.method || 'GET';
        var url = parameters.url;
        var async = parameters.async || true;
        var func = parameters.success || null;
        var cache = parameters.cache || false;

        var t = '';
        if(parm != null){
            for(var key in parm){
                t += '&' + key + '=' + encodeURIComponent(parm[key]);
            }
            if(t != '') t = t.substring(1);
            if(t != '' && !cache) t += '&'+Date();
        }
        
        method = method.toLowerCase();
        
        var xmlhttp = this._create();
        if(xmlhttp){
            try{
                if(method == 'get'){
                    if(t != '') url += '?' + t;
                    parm = null;
                }
                xmlhttp.open(method, url, async);
                if(!cache) xmlhttp.setRequestHeader('cache-control', 'no-cache');
                if(method == 'post'){
                    xmlhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded; charset=utf-8');
                    parm = t;
                }
                xmlhttp.onreadystatechange = function(){
                    if(xmlhttp.readyState == 4){
                        if(xmlhttp.status == 200){
                            if(func != null) func(xmlhttp);
                            xmlhttp = null;
                        }
                    }
                }
                xmlhttp.send(parm);
            }catch(e){ alert(e.toString()); }
        }
    }
}

