﻿
var _ajaxRequestList = new Array();

kagetuAjaxRequest = function(url,onready,onload,onerror,method,params,contentType){
  var ajaxRequest = new Array();
  ajaxRequest[0] = url;
  ajaxRequest[1] = onready;
  ajaxRequest[2] = onload;
  ajaxRequest[3] = onerror;
  ajaxRequest[4] = method;
  ajaxRequest[5] = params;
  ajaxRequest[6] = contentType;
  
  _ajaxRequestList.push(ajaxRequest);
  
  if(_ajaxRequestList.length == 1){   
    kagetuAjaxRequest.sentRequest("str");
  }  
}

kagetuAjaxRequest.sentRequest = function(str){
  if(_ajaxRequestList.length > 0){
    new kagetuAjax(_ajaxRequestList[0][0], _ajaxRequestList[0][1], _ajaxRequestList[0][2], _ajaxRequestList[0][3],
      _ajaxRequestList[0][4], _ajaxRequestList[0][5], _ajaxRequestList[0][6]);
  }  
}

kagetuAjax = function(url,onready,onload,onerror,method,params,contentType){
  this.req = null;
  this.onload = onload;
  this.onready = onready;
  this.onerror = (onerror) ? onerror : this.defaultError;
  this.loadXMLDoc(url, method, params, contentType);
}

kagetuAjax.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();   
        
    if (this.req.overrideMimeType){
      this.req.overrideMimeType("text/xml");
    }
  } 
  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(){
        kagetuAjax.onReadyState.call(loader);
      }
      this.req.open(method,url,true);
      if (contentType){
        this.req.setRequestHeader('Content-Type', contentType);
      }
      this.req.send(params);
    }
    catch (err){
      this.onerror.call(this);
    }
  }
  else{
    window.alert("创建XMLHttpRequest对象实例失败,当前浏览器不兼容。");
    return false;
  }
}

kagetuAjax.onReadyState=function(){
  var req=this.req;
  var ready=req.readyState;

  if (ready == 4){ 
    var httpStatus=req.status;
    
    if (httpStatus==200 || httpStatus==0){
      this.onload.call(this);
    }
    else{
      this.onerror.call(this);
    }    
    _ajaxRequestList.shift(); 
    kagetuAjaxRequest.sentRequest("str");
  }
  else{    
    this.onready.call(this);
  }  
}

kagetuAjax.prototype.defaultError=function()
{
  alert("网络忙！请点击确定后重试！"
    + "\n若错误重复出现！请联系站长！"
    + "\nerror fetching data!"
    + "\n\nreadyState:"+this.req.readyState
    + "\nstatus: "+this.req.status
    + "\nheaders: "+this.req.getAllResponseHeaders());
}




