﻿//
/*
 * 返回一个新建的XMLHttpRequest对象，若浏览器不支持则失败
*/
function newXMLHttpRequest() {
  var xmlreq = false;
  if (window.XMLHttpRequest) {
    // 在非Microsoft浏览器中创建XMLHttpRequest对象
    xmlreq = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    //通过MS ActiveX创建XMLHttpRequest
    try {
      // 尝试按新版InternetExplorer方法创建
      xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e1) {
      // 创建请求的ActiveX对象失败
      try {
        // 尝试按老版InternetExplorer方法创建
        xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
        // 不能通过ActiveX创建XMLHttpRequest
      }
    }
  }
  return xmlreq;
}

/*
 * 将客户端访问数据发送请求
 * param – 需要的记录参数
 */
function getResponse(Url,obj) 
{
  // 获取一个XMLHttpRequest实例
  var req = newXMLHttpRequest();
  
  var handlerFunction = getReadyStateHandler(req,obj);
  req.onreadystatechange = handlerFunction;
  // 设置用来从请求对象接收回调通知的句柄函数
  req.open("GET", Url, true);
  req.setRequestHeader("Content-Type","text/html;charset=GB2312;");
  req.send(null);
}

function getPostResponse(Url,obj,postStr)
{
    // 获取一个XMLHttpRequest实例
  var req = newXMLHttpRequest();
  
  var handlerFunction = getReadyStateHandler(req,obj);
  req.onreadystatechange = handlerFunction;
  // 设置用来从请求对象接收回调通知的句柄函数
  req.open("Post", Url, true);
  req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  req.send(postStr);
}
/*
 * Returns a function that waits for the specified XMLHttpRequest
 * to complete, then passes its XML response to the given handler function.
 * req - The XMLHttpRequest whose state is changing
 * responseXmlHandler - Function to pass the XML response to
 */
function getReadyStateHandler(req,obj) {
  // 返回一个监听XMLHttpRequest实例的匿名函数
  return function () {
    // 如果请求的状态是“完成”
    if (req.readyState == 4) {
      // 检查是否成功接收了服务器响应
      if (req.status == 200) {
        // 将载有响应信息的XML传递到处理函数
        obj.innerHTML = req.responseText;
      } else {
        // 有HTTP问题发生
        alert("HTTP error: "+req.status);
      }
    }
  }
}