DIV CSS 佈局教程網

JavaScript Ajax 編程:從 XHR 到 FormData 的實戰
編輯:關於JavaScript     

Ajax(Asynchronous JavaScript + XML)讓我們能在不卸載頁面的前提下向伺服器索取額外資料,也就是所謂的局部刷新。本文從建立 XHR 物件開始,把 GET、POST、請求頭、進度事件等環節完整走一遍。

一、建立跨瀏覽器的 XHR 物件

 function createXHR() {
  if (typeof XMLHttpRequest != "undefined") {
    return new XMLHttpRequest();
  } else if (typeof ActiveXObject != "undefined") {   // 舊版 IE
    if (typeof arguments.callee.activeXString != "string") {
      var version = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"];
      for (var i = 0, len = version.length; i < len; i++) {
        try {
          new ActiveXObject(version[i]);
          arguments.callee.activeXString = version[i];
          break;
        } catch (ex) {}
      }
    }
    return new ActiveXObject(arguments.callee.activeXString);
  } else {
    throw new Error("No Support For XHR");
  }
}

二、基本用法:同步請求

open() 接受三個參數:請求方法(get/post 等)、請求 URL、是否非同步。send() 接受一個參數作為請求主體,不需要時傳 null。

 var xhr = createXHR();
xhr.open("get", "example.txt", false);   // 同步
xhr.send(null);

if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
  alert(xhr.responseText);   // example.txt 內容為 123456
} else {
  alert("Request was unsuccessful: " + xhr.status);
}

304 代表命中瀏覽器快取,也屬於成功的一種。

三、非同步請求

 var xhr = createXHR();
// readyState 為 4 代表響應資料已全部接收完畢
xhr.onreadystatechange = function () {
  if (xhr.readyState == 4) {
    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
      alert(xhr.responseText);
    } else {
      alert("Request was unsuccessful: " + xhr.status);
    }
  }
};
xhr.open("get", "example.txt", true);
xhr.send(null);

四、請求頭與響應頭

瀏覽器送 XHR 請求時預設會帶上 Accept、Accept-Charset、Accept-Encoding、Accept-Language、Connection、Cookie、Host、Referer、User-Agent 等標頭。若要自訂,用 setRequestHeader(),它接受標頭名稱與值兩個參數,且必須在 open() 之後、send() 之前呼叫。

 xhr.open("get", "example.txt", true);
xhr.setRequestHeader("name", "zhang");
xhr.send(null);

讀取響應標頭則用 getResponseHeader() 取單一欄位,getAllResponseHeaders() 取全部:

 xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
    var contentType = xhr.getResponseHeader("Content-Type");  // text/plain
    var all = xhr.getAllResponseHeaders();
    alert(all);
  }
};

五、為 GET 請求拼接參數

 /**
 * @param url 不含參數的 url
 * @param name 參數名
 * @param value 參數值
 * @returns 帶參數的 url
 */
function addURLParam(url, name, value) {
  url += (url.indexOf("?") == -1 ? "?" : "&");
  url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
  return url;
}

var url = addURLParam("example.txt", "name", "zhang");
url = addURLParam(url, "age", "23");
// 結果:example.txt?name=zhang&age=23

動手做編碼這件事很重要,直接字串串接中文或特殊字元很容易出問題。

六、POST 請求:即時校驗用戶名的完整案例

場景是註冊頁:使用者在用戶名輸入框失焦時,非同步向後端查詢該名稱是否已被佔用,並即時顯示綠色或紅色提示。

頁面結構:

 <form name="myForm" method="post">
姓名:<input type="text" name="username" /><label id="userLabel">請輸入用戶名</label><br/>
密碼:<input type="password" name="password" /><br/>
<input type="submit" value="登錄" />
</form>

事件封裝:

 var EventUtil = {
  addEvent: function (element, type, handler) {
    if (element.addEventListener) {
      element.addEventListener(type, handler, false);
    } else if (element.attachEvent) {
      element.attachEvent("on" + type, handler);
    }
  }
};

表單序列化(把表單內容轉成 a=1&b=2 形式的查詢字串):

 function serialize(form) {
  var parts = [], field, i, len, j, optLen, option, optValue;
  for (i = 0, len = form.elements.length; i < len; i++) {
    field = form.elements[i];
    switch (field.type) {
      case "select-one":
      case "select-multiple":
        if (field.name.length) {
          for (j = 0, optLen = field.options.length; j < optLen; j++) {
            option = field.options[j];
            if (option.selected) {
              optValue = option.hasAttribute
                ? (option.hasAttribute("value") ? option.value : option.text)
                : (option.attributes["value"].specified ? option.value : option.text);
              parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(optValue));
            }
          }
        }
        break;
      case undefined:  // 欄位集
      case "file":
      case "submit":
      case "reset":
      case "button":
        break;
      case "radio":
      case "checkbox":
        if (!field.checked) break;
        /* falls through */
      default:
        if (field.name.length) {
          parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value));
        }
    }
  }
  return parts.join("&");
}

核心操作:

 var form = document.forms[0];
var username = form.elements['username'];
var userLabel = document.querySelector("#userLabel");

EventUtil.addEvent(username, "blur", function () {
  var xhr = createXHR();
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
        if (xhr.responseText) {
          userLabel.style.color = "green";
          userLabel.firstChild.data = "恭喜你,用戶名可用";
        } else {
          userLabel.style.color = "red";
          userLabel.firstChild.data = "對不起,該用戶已存在";
        }
      }
    }
  };
  xhr.open("post", "check.php", true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.send(serialize(form));
});

用 FormData 取代手寫序列化。XMLHttpRequest 第二版定義了 FormData 型別,會自動序列化表單,程式碼大幅精簡:

 xhr.open("post", "check.php", true);
xhr.send(new FormData(form));   // 這時不需要手動設定 Content-Type

七、其他值得知道的 API

超時設定:

 xhr.open("get", "example.txt", true);
xhr.timeout = 1000;
xhr.ontimeout = function () { alert("請求超過 1 秒未返回"); };
xhr.send(null);

覆寫 MIME 型別:

 xhr.open("get", "example.txt", true);
xhr.overrideMimeType("text/xml");   // 原本回傳 text/plain
xhr.send(null);

進度事件:load 在收到響應時觸發,可取代 onreadystatechange;progress 則在接收資料期間週期性觸發,適合用來做進度條。

 var xhr = createXHR();
xhr.onprogress = function (event) {
  var divStatus = document.getElementById("status");
  if (event.lengthComputable) {
    divStatus.innerHTML = "已接收 " + event.position + " / " + event.totalSize + " bytes";
  }
};
xhr.onload = function () {
  if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
    alert(xhr.responseText);
  }
};
xhr.open("get", "large-file.txt", true);
xhr.send(null);

最後補充一個實務判斷:如果不是要處理二進位資料或需要精細控制請求過程,現在的專案多半直接用 fetch 或 axios,語意更清楚、Promise 化的錯誤處理也更乾淨。理解 XHR 這層機制的價值在於除錯與讀懂舊專案,而非繼續手寫。

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