DIV CSS 佈局教程網

給初學者的 Ajax 通用函式:一個 option 物件搞定 GET 與 POST
編輯:AJAX基礎知識     

每次寫 Ajax 都要重複建立物件、設定標頭、寫狀態判斷,很膩。把它包成一個函式,用物件傳參數,之後呼叫就只剩一行。這份程式碼適合初學者直接拿去用。

怎麼呼叫

先準備資料與設定物件,再呼叫 ajax(option):

// POST 方式
var txt = escape(sender.value);
var data = "name=" + txt + "&pwd=" + txt;
var option = {
  "url": "handler/Handler.ashx",
  "action": "POST",
  "callback": function(){
    if(xmlHttp.readyState == 4){        // 伺服器已回應
      if(xmlHttp.status == 200){        // 伺服器正確回應
        alert(xmlHttp.responseText);
      }
      xmlHttp = null;                   // 回收資源
    }
  },
  "data": data
};
ajax(option);

// GET 方式(參數直接接在網址後面,不需要 data)
var option = {
  "url": "handler/Handler.ashx&name=" + txt + "&pwd=" + txt,
  "action": "POST",
  "callback": function(){
    if(xmlHttp.readyState == 4){
      if(xmlHttp.status == 200){
        alert(xmlHttp.responseText);
      }
      xmlHttp = null;
    }
  }
};
ajax(option);

主函式

function ajax(option) {
  createXMlHttpRequest();               // 建立 xmlHttpRequest 物件
  if(option != null && option != undefined){
    if(option.url == null || option.url == undefined){
      xmlHttp = null;
      alert("缺少必要參數 option.url");
      return;
    }
    if(option.action == null || option.action == undefined){
      xmlHttp = null;
      alert("缺少必要參數 option.action");
      return;
    }
    xmlHttp.open(option.action, option.url, true);

    if(option.contentType != null && option.contentType != undefined){
      xmlHttp.setRequestHeader("Content-Type", option.contentType);
    }else{
      xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    }

    if(option.callback != null && option.callback != undefined){
      xmlHttp.onreadystatechange = option.callback;
    }

    if(option.action.toUpperCase() == "POST"){
      xmlHttp.send(option.data);        // POST 要送資料
    }else{
      xmlHttp.send(null);               // GET 不送
    }
  }
}
var xmlHttp;   // 呼叫完成後最好回收一下:xmlHttp = null;

輔助函式

/* 取得元素 */
function g(arg) {
  var t = document.getElementById(arg);
  if(null != t && t != undefined){ return t; }
  t = document.getElementsByName(arg);
  if(null != t && t != undefined){ return t; }
  t = document.getElementsByTagName(arg);
  if(null != t && t != undefined){ return t; }
}

/* 建立 ajax 請求物件 */
function createXMlHttpRequest() {
  try {                                   // Firefox, Chrome, Safari, Opera 8+
    xmlHttp = new XMLHttpRequest();
  }catch(ie){
    try {                                 // IE6+
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(ie){
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  return xmlHttp;
}

這個設計好在後面

把「請求方式、網址、要送的資料、成功後要做什麼」全部收進一個物件,呼叫端就不必再關心 XHR 的細節。contentType 給了預設值,callback 是選填,action 會自動判斷要不要送 data——這些都是讓呼叫端更省事的小設計。

可以怎麼改進

這份程式有幾個地方值得優化成現代寫法:

  1. xmlHttp 是全域變數,多個併發請求會互相覆蓋。改成函式內的區域變數、或透過閉包傳回,才是安全的做法。
  2. 錯誤處理太薄。目前只檢查 status == 200,建議加上 onerror 與逾時處理,並把非 200 的狀態碼交給呼叫端決定怎麼顯示。
  3. GET 的參數拼接有問題。範例中 "handler/Handler.ashx&name=" 用了 & 開頭,第一個參數應該是 ?。建議用 URLSearchParams 組字串,避免自己處理分隔符號。
  4. escape 已不建議使用,改用 encodeURIComponent 才能正確處理非 ASCII 字元。
  5. callback 裡判斷 readyState 的責任目前落在呼叫端,每個 callback 都要重寫一次。可以在主函式裡統一判斷,只把解析後的結果或錯誤傳給 callback。

若是新專案,直接用 fetch 搭配 async/await 會比這份封裝簡潔得多;需要維護舊系統時,這個模式仍然是很好的起點。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved