Ajax 實例化封裝

function AjaxUtil(){
}

/**
 * 實例化request對象
 */
AjaxUtil.instanceRequest = function() {
 var _httpRequest = null;
 // 開始初始化XMLHttpRequest對象
 if(window.XMLHttpRequest) { // FireFox 瀏覽器
    _httpRequest = new XMLHttpRequest();
    if (_httpRequest.overrideMimeType) {// 設置MiME類別
     _httpRequest.overrideMimeType('text/xml');
    }
 }else if (window.ActiveXObject) { // IE瀏覽器
    try {
        _httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
                _httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
    }
 }
 if (!_httpRequest) { // 異常,創建對象實例失敗
   window.alert("不能創建XMLHttpRequest對象實例.");
 }
 return _httpRequest;
}

/**
 * 發送請求
 *
 * @param $method
 *            "GET/POST"
 * @param $url
 *            請求路徑
 * @param $isAsync
 *      "true/false"
 * @param $params
 *            請求參數
 * @param $processMethod
 *            處理(請求結果的)方法
 */
AjaxUtil.sendRequest = function($method, $url, $isAsync, $params, $processMethod) {
 try {
  // 實例化請求
  var requestObj = AjaxUtil.instanceRequest();
  if (requestObj != null) {
   requestObj.onreadystatechange = processRequest;
   requestObj.open($method, $url, $isAsync);
   requestObj.send($params);
  }
  
  // 處理請求
  function processRequest(){
   if (requestObj.readyState == 4) {
    if (requestObj.status == 200) {
     // 執行目標方法
     eval($processMethod);
    }
   }
  }
 } catch (e) {
  alert(e.description);
 }  
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章