﻿/*
日期：2009.4.15
ajax调度，
*/
function ajaxCB(){
    this.xmlhttp=false;
    if(window.ActiveXObject){
        try{
            this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e) {
            try{
                this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }catch(e){this.xmlhttp=false;}
        }
    }
    else try{
        this.xmlhttp = new XMLHttpRequest();
    }catch(e){this.xmlhttp=false;}
//    try{this.xmlhttp=window.ActiveXObject?new ActiveXObject('Microsoft.XMLHTTP'):new XMLHttpRequest();}
//    catch(e){this.xmlhttp=false;}
    
    if(this.xmlhttp===false)return false;
    
    this.onStart=new Function();
    this.onDoing=new Function();
    this.onError=new Function();
    this.onAbort=new Function();
    this.onFinish=new Function();
    var self=this;
    this.onreadystatechange=function(){
        if(self.xmlhttp.readyState==4){
//            clearInterval(self.timeid);
            if(self.xmlhttp.status==0) self.onAbort();
            else if(self.xmlhttp.status==200) self.onFinish(self.xmlhttp.responseText);
            else self.onError();
        }
    }
    this.callBack=function(method,url,para){    
        if( this.xmlhttp.readyState == 4 || this.xmlhttp.readyState == 0 )
        {
            method=method.toUpperCase();
            if(method=='GET')para['removeCache']=new Date().valueOf();// 由于 get 时，相同的url会产生缓存
            var sp=toDoPara(para);
            if(method=='GET'){url+="?"+sp;sp=null;}
            else if(sp=='')sp=null;
            if(this.onStart) this.onStart();
            this.xmlhttp.open(method,url);
            this.xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=utf-8');
            this.xmlhttp.setRequestHeader("If-Modified-Since","Thu, 01 Jan 1970 00:00:00 GMT" );
            this.xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            this.xmlhttp.setRequestHeader("Accept","*/*");
            this.xmlhttp.onreadystatechange = function(){ self.onreadystatechange(); };
            //this.timeid=setInterval(this.onreadystatechange,80);
            this.xmlhttp.send(sp);
        }
    }
    this.get=function(url,para){
        if(!para){para=url;url=getAjaxURL();}
        this.callBack('get',url,para);
    };
    this.post=function(url,para){
        if(!para){para=url;url=getAjaxURL();}
        this.callBack('post',url,para);
    };
    // tools
    function toDoPara(para){
        var r='';
        if(!para)return '';
        
        for(var p in para) r+=(r==''?'':'&')+p+'='+para[p];//encodeURIComponent(para[p]);
        return r;
    }
    function getAjaxURL(){
        if(window.location.href.indexOf('localhost')>=0)return '/BookSite/Tools/ajax.aspx';
        return '/Tools/ajax.aspx';
    }
}
ajaxCB.convertToObject=function(s){var ob=eval('('+s+')');return ob;}
