ajax 操作

 

Code

 

 

/*---------------------Ajax请求页面并将返回值赋给某元素--------------------------*/

function SendToPageFillElement(ElementID,url,data)
{
 this.ElementType = 1;//填充元素的类型  1:Div文本  2:Div的HTML  3:Input的value
 this.Chunnel = null;//Ajax通道
 var ElementTypeV = this.ElementType;
 var SendCallBack = function mycallback(obj)
 {
  var ElementItem = $(ElementID);
  var ReturnText = obj.responseText;
  switch (ElementTypeV)
  {
   case 1:
    if(navigator.appName.indexOf("Explorer") > -1)//IE
    {
     ElementItem.innerText = ReturnText;
    }
    else//FireFox
    {
     ElementItem.textContent = ReturnText;
    }
    break;
   case 2:
    ElementItem.innerHTML = ReturnText;
    break;
   case 3:
    ElementItem.value = ReturnText;
    break;
  }
 }
 this.SendData = function()
 {
  Request.SendToPage(url,data,SendCallBack,true,this.Chunnel);
 }
}

/*------------------------------Ajax消息提示---------------------------*/
document.write('<div id="AjaxMessageDiv" style="height:0px;overflow:hidden;"><spacer></spacer></div>')
function Message_Div(MessageIdentity)
{
 MessageIdentity = MessageIdentity + Math.random().toString().replace('0.','');
 eval('window.obj' + MessageIdentity + ' = this');
 this.Timer1 = null;
 this.Timer2 = null;
 this.MessageText = '请设置MessageText属性';//提示文字
 this.FontColor = '#ffffff';//文字颜色
 this.FontSize = '12px';
 this.BgColor = '#EA5006';//提示文字背影颜色
 this.Width = '220px';//提示框宽度
 this.Height = '18px';//提示框高度
 this.ReferencePoint = 0;//位置参考点  0:窗体中的绝对位置  1:某控件的位置
 this.ReferenceControlName = '';//当ReferencePoint=1时才起作用,为控件的名称
 this.RelativelyPointX = '0px';//相对于ReferencePoint的横向X距离
 this.RelativelyPointY = '0px';//相对于ReferencePoint的纵向Y距离
 this.Disappear = 0;//消失模式     0:不消失  1:渐渐消失  2:透明度闪烁
 this.DisappearMillisecond = 30;//渐渐消失速度(毫秒)越小则越快
 this.CycDivCount = 0;//闪烁的次数  0:无限闪烁
 this.CycMillisecond = 15;
 
 //立即隐藏Message
 this.HiddenMessage = function()
 {
  $('MessageDiv' + MessageIdentity).style.display = 'none';
 }
 //主运行函数  MessageIdentity:代表页面中提示的标识ID
 this.ShowMessage = function()
 {
  window.clearInterval(this.Timer1);
  window.clearInterval(this.Timer2);
  if (this.MessageText == '')
  {
   return;
  }
  var MessageDiv = $('MessageDiv' + MessageIdentity);
  if (!MessageDiv)
  {
   $('AjaxMessageDiv').innerHTML += '<div id="MessageDiv' + MessageIdentity + '" style="DISPLAY: none;Z-INDEX: 99;POSITION: absolute;FILTER: alpha(opacity=100); text-align:center"></div>';
   MessageDiv = $('MessageDiv' + MessageIdentity);
  }
  if ( !MessageDiv.filters )//FireFox
  {
   MessageDiv.style.opacity = 1;
  }
  else//IE
  {
   MessageDiv.filters.alpha.opacity = 100;//将透明度恢复为100
  }
  MessageDiv.style.color = this.FontColor;
  if(navigator.appName.indexOf("Explorer") > -1)//IE
  {
   MessageDiv.innerText = this.MessageText;
  }
  else//FireFox
  {
   MessageDiv.textContent = this.MessageText;
  }
  MessageDiv.style.fontSize = this.FontSize;
  MessageDiv.style.backgroundColor = this.BgColor;
  MessageDiv.style.width = this.Width;
  MessageDiv.style.height = this.Height;
  MessageDiv.style.lineHeight = this.Height;
  var PositionX;//相对于窗体的X值
  var PositionY;//相对于窗体的Y值
  switch (this.ReferencePoint)
  {
   case 0:
    PositionX = this.RelativelyPointX;
    PositionY = this.RelativelyPointY;
    break;
   case 1:
    var ReferenceControl = $(this.ReferenceControlName);
    //获取相对于窗口的x y 值
    var winOffsetX = ReferenceControl.offsetTop;
    var winOffsetY = ReferenceControl.offsetLeft;
    //当ReferenceControl包含在其它Html元素或控件中时,正确计算x y 值
    while (ReferenceControl = ReferenceControl.offsetParent){winOffsetX += ReferenceControl.offsetTop; winOffsetY += ReferenceControl.offsetLeft;}
    PositionX = CountPx(this.RelativelyPointX,winOffsetY);
    PositionY = CountPx(this.RelativelyPointY,winOffsetX);
    //MessageDiv.style.display = '';
    //MessageDiv.style.top = winOffsetX;
    //MessageDiv.style.left = winOffsetY + ControlW;
    break;
  }
  MessageDiv.style.top = PositionY;
  MessageDiv.style.left = PositionX;
  MessageDiv.style.display = '';
  var IsFF;
  if (!MessageDiv.filters)
  {
   IsFF = true;
  }
  else
  {
   IsFF = false;
  }
  switch (this.Disappear)
  {
   case 1:
    //this.MessageDivOpacityOdd(MessageIdentity);
    window.clearInterval(this.Timer1);
    this.Timer1 = window.setInterval("window.obj" + MessageIdentity + ".MessageDivOpacityOdd(" + IsFF + ")",this.DisappearMillisecond);
    break;
   case 2:
    window.clearInterval(this.Timer2);
    this.Timer2 = window.setInterval("window.obj" + MessageIdentity + ".MessageDivOpacityRay(" + this.CycDivCount + "," + IsFF + ")",this.CycMillisecond);
    break;
  }
 }
 this.MessageDivOpacityOdd = function(IsFF)
 {
  var MessageDiv = $('MessageDiv' + MessageIdentity);
  if ( IsFF )//FireFox
  {
   if (MessageDiv.style.opacity > 0)
   {
    MessageDiv.style.opacity -= 0.01;
   }
   else
   {
    MessageDiv.style.display = 'none';
    window.clearInterval(this.Timer1);
   }
  }
  else//IE
  {
   if (MessageDiv.filters.alpha.opacity > 0)
   {
    MessageDiv.filters.alpha.opacity -= 1;
   }
   else
   {
    MessageDiv.style.display = 'none';
    window.clearInterval(this.Timer1);
   }
  }
 }
 var upordown = 0;
 var CycCount = 0;//当前循环了多少次
 this.MessageDivOpacityRay = function(myCount,IsFF)//myCount总共闪烁几次,如果为0则为无限闪烁
 {
  var MessageDiv = $('MessageDiv' + MessageIdentity);
  if ( IsFF )//FireFox
  {
   if ( myCount != 0 && CycCount > myCount )
   {
    window.clearInterval(this.Timer2);
    MessageDiv.style.display = 'none';
    return;
   }
   switch ( upordown )
   {
    case 1:
     if(MessageDiv.style.opacity != 1 )
     {
      MessageDiv.style.opacity = 1;    
     }
     else
     {
      upordown = 0;
     }
     break;
    case 0:
     if(MessageDiv.style.opacity <= 1 && MessageDiv.style.opacity>=0.1   )
     {
      MessageDiv.style.opacity -= 0.03;  
     }
     else
     {
      CycCount++;
      upordown = 1;
     }
     break;
   } 
  }
  else//IE
  {
   if ( myCount != 0 && CycCount > myCount )
   {
    window.clearInterval(this.Timer2);
    MessageDiv.style.display = 'none';
    return;
   }
   switch ( upordown )
   {
    case 1:
     if(MessageDiv.filters.alpha.opacity != 100 )
     {
      MessageDiv.filters.alpha.opacity += 3;
     }
     else
     {
      upordown = 0;
     }
     break;
    case 0:
     if(MessageDiv.filters.alpha.opacity <= 100 && MessageDiv.filters.alpha.opacity>=10   )
     {
      MessageDiv.filters.alpha.opacity -= 3;  
     }
     else
     {
      CycCount++;
      upordown = 1;
     }
     break;
   } 
  }
 }
}


//将两个px字符型的变量相加,返回的数字仍然是后带px
function CountPx(PxA,PxB)
{
 return (parseInt(PxA.toString().replace('px','')) + parseInt(PxB.toString().replace('px',''))).toString() + 'px';
}


/**
 * 函数 $
 * 功能 获取dhtml对象
 * 参数 e 待查找的对象id或name
 * 返回 成功:对象 失败:null
 */
function $(e) {
  var tag = document.getElementById(e);
  if(tag) return tag;
  tag = document.getElementsByName(e);
  if(tag.tagName == undefined) return null;
  return tag;
}

function CreaeXMLDOM()
{
    var MSDOM = ['MSXML2.DOMDocument.4.0', 'MSXML2.DOMDocument.3.0', 'MSXML2.DOMDocument.2.6', 'MSXML2.DOMDocument', 'Microsoft.XMLDOM'];
    var XMLDOM;
    for(var n = 0; n < MSDOM.length; n++)
    {
        try
        {
            XMLDOM = new ActiveXObject(MSDOM[n]);
            break;
        }
        catch(e)
        {
        }
    }
    if(typeof(XMLDOM) != "object")
  XMLDOM = document.implementation.createDocument("text/xml", "", null);
    if(typeof(XMLDOM) != "object")
        alert('创建XMLDOM对象失败,请升级您的浏览器');
    return XMLDOM;
}

function GetXmlNodeValue(objXmlElement)
{
    var str = "";
    if(window.XMLHttpRequest)        //Mozilla
    {
        try
        {
            str = objXmlElement.firstChild.nodeValue;
        }
        catch(ex)
        {
   alert(ex);
            str = "";
        }
    }
    else if(window.ActiveXObject)    //IE
    {
        str = objXmlElement.text;
    }
    return str;
}

if( document.implementation.hasFeature("XPath", "3.0") )
{

XMLDocument.prototype.loadXML = function(xmlString)
{
    var childNodes = this.childNodes;
    for (var i = childNodes.length - 1; i >= 0; i--)
        this.removeChild(childNodes[i]);

    var dp = new DOMParser();
    var newDOM = dp.parseFromString(xmlString, "text/xml");
    var newElt = this.importNode(newDOM.documentElement, true);
    this.appendChild(newElt);
}

// prototying the Element
Element.prototype.selectNodes = function(cXPathString)
{
    if(this.ownerDocument.selectNodes)
    {
        return this.ownerDocument.selectNodes(cXPathString, this);
    }
    else{throw "For XML Elements Only";}
}

 

XMLDocument.prototype.selectNodes = function(cXPathString, xNode)
       {
          if( !xNode ) { xNode = this; }
          var oNSResolver = this.createNSResolver(this.documentElement)
          var aItems = this.evaluate(cXPathString, xNode, oNSResolver,
                       XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
          var aResult = [];
          for( var i = 0; i < aItems.snapshotLength; i++)
          {
             aResult[i] =  aItems.snapshotItem(i);
          }
          return aResult;
       }

 Element.prototype.selectSingleNode = function(cXPathString)
       {   
          if(this.ownerDocument.selectSingleNode)
          {
             return this.ownerDocument.selectSingleNode(cXPathString, this);
          }
          else{throw "For XML Elements Only";}
       }


XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode)
       {
          if( !xNode ) { xNode = this; }
          var xItems = this.selectNodes(cXPathString, xNode);
          if( xItems.length > 0 )
          {
             return xItems[0];
          }
          else
          {
             return null;
          }
       }
}

 

/** */
var Request = new function(){

this.pool = new Array();

//建立XMLHttp对像,并处理通道
this.getXMLHttp = function (chunnel)
{
 
 if(chunnel != null)
 {
  for (var a = 0; a < this.pool.length; a++)
  {
   if(this.pool[a]["chunnel"] == chunnel)
   {
 if(this.pool[a]["obj"].readyState == 0 || this.pool[a]["obj"].readyState == 4)
    {
     return this.pool[a]["obj"];
    }
 else
 {
      return "busy";
 }
   }
  }
 
  this.pool[this.pool.length] = new Array();
  this.pool[this.pool.length - 1]["obj"] = this.createXMLHttp();
  this.pool[this.pool.length - 1]["chunnel"] = chunnel;
  return this.pool[this.pool.length - 1]["obj"];
 
 }
 
 for (var i = 0; i < this.pool.length; i++)
 {
  if (this.pool[i]["obj"].readyState == 0 || this.pool[i]["obj"].readyState == 4)
  {
   return this.pool[i]["obj"];
  }
 }
 
 this.pool[this.pool.length] = new Array();
 this.pool[this.pool.length - 1]["obj"] = this.createXMLHttp();
 this.pool[this.pool.length - 1]["chunnel"] = "";
 return this.pool[this.pool.length - 1]["obj"];

}

this.createXMLHttp = function ()
{
 
 if(window.XMLHttpRequest)
 {
  var xmlObj = new XMLHttpRequest();
 }
 else
 {
  var MSXML = ['Microsoft.XMLHTTP', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
  for(var n = 0; n < MSXML.length; n++)
  {
   try
   {
    var xmlObj = new ActiveXObject(MSXML[n]);       
    break;
   }
   catch(e)
   {
   }
  }
 }
 
 return xmlObj;

}

//主运行部分  IsAsynchronous是否为异步方式  异步:后面的代码无需等待此回调执行完毕   同步:等待XmlHttp返回结果后再继续执行
this.SendToPage = function (url,data,callback,IsAsynchronous,chunnel)
{
 var objXMLHttp = this.getXMLHttp(chunnel)
 
 //创建XMLHTTP对象失败
 if(typeof(objXMLHttp) != "object")
 {
 if (objXMLHttp == 'busy')
 {
  alert('您的上次操作还没有完成,请稍候再进行此操作');
 }
 else
 {
  alert('请升级您的浏览器');
 }
  return ;
 }
 
 //解决XMLHTTP请求时浏览器缓存的问题
 url += (url.indexOf("?") >= 0) ? "&nowtime=" + new Date().getTime() : "?nowtime=" + new Date().getTime();

 if(data == "")
 {
  objXMLHttp.open('GET' , url, IsAsynchronous);
  objXMLHttp.send('');
 }
 else
 {
  objXMLHttp.open('POST' , url, IsAsynchronous);
  //为Post时,需要设置一下XMLHTTP的头
  objXMLHttp.setRequestHeader("Content-Length",data.length);
  objXMLHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded charset=utf-8");
  objXMLHttp.send(data);
 }
 //处理回调函数
 if(typeof(callback) == "function" )
 {
    if (IsAsynchronous)
    {
        objXMLHttp.onreadystatechange = function ()
          {
           if (objXMLHttp.readyState == 4)
           {
            if(objXMLHttp.status == 200 || objXMLHttp.status == 304)
            {
    callback(objXMLHttp,'');
            }
            else
            {
             //alert("发生错误:\n"+ objXMLHttp.status +":"+ objXMLHttp.statusText);
             callback(null,'发生错误:' + objXMLHttp.status +":"+ objXMLHttp.statusText);
            }
           }
          }
    }
    else
    {
       if (objXMLHttp.readyState == 4)
       {
        if(objXMLHttp.status == 200 || objXMLHttp.status == 304)
        {
          callback(objXMLHttp,'');
        }
        else
        {
         //alert("发生错误:\n"+ objXMLHttp.status +":"+ objXMLHttp.statusText);
         callback(null,'发生错误:' + objXMLHttp.status +":"+ objXMLHttp.statusText);
        }
       }
    }
 }

}

}

var DateTime = new function ()
{
   var d = new Date();
   var s;
   s = d.getYear() + '-';
   s += (d.getMonth() + 1) + "-";
   s += d.getDate();
   this.Now = s;
}

/*--------------------------IE  FireFox 兼容------------------------*/
//innerText
if(typeof HTMLElement!="undefined"){
        HTMLElement.prototype.innerText
        getter = function(){
                return this.textContent;
        }

        HTMLElement.prototype.innerText
        setter = function(txtStr){
                this.textContent = txtStr
        }
}

你可能感兴趣的:(Ajax)