每次寫 Ajax 都要重複一遍「建立物件、判斷瀏覽器、設定回呼」,久了實在煩。與其如此,不如把流程封裝成一個可重複使用的物件。以下這個版本同時支援 GET 與 POST,並把失敗處理也一起包了進去。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Ajax Document</title>
<script type="text/javascript">
// 注意:頁面編碼必須統一為 utf-8,才能避免中文參數與中文回值的亂碼問題
function Ajax(prop){
this.action(prop); // 實例化時即觸發 action 方法
}
Ajax.prototype = {
createXHR: function(){ // 建立 XMLHttpRequest 物件
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xhr;
},
action: function(prop){
var xhr = this.createXHR();
if (xhr) {
var url = encodeURI(prop["url"]); // 對 URL 進行編碼
if (prop["method"] == "GET" && url && prop["success"]) { // GET 方法
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200) {
prop["success"](xhr); // 執行回呼函式
}
};
xhr.open("GET", url, true);
xhr.send(null);
}
else if (prop["method"] == "POST" && url && prop["success"]) { // POST 方法
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200) {
prop["success"](xhr);
}
};
if (prop["params"]) {
url = url.indexOf("?") > -1 ? url + "&" + prop["params"] : url + "?" + prop["params"];
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(null);
}
}
else if (!xhr && prop["fail"]) {
prop["fail"]();
}
}
}
function getData(){
new Ajax({
url: "test.php",
method: "POST",
success: onComplete,
params: "name=" + escape("沙鋒") // 傳送前先編碼
});
}
function onComplete(obj){
alert(unescape(obj.responseText)); // 接收後再轉碼回來
}
</script>
</head>
<body>
<input type="button" value="Get Data" onclick="getData()"/>
</body>
</html>
Ajax 物件接受一個物件字面值作為參數,其中包含下列欄位:
"GET" 或 "POST"第一,中文參數必須 encode/decode 成對使用,且頁面編碼要統一為 UTF-8,這是最常見的亂碼來源。第二,範例中的 POST 分支把參數拼在網址後方而非放在 send() 裡,這樣寫雖然能運作,但不符合 POST 的語意,實務上建議改成 xhr.send(prop["params"])。第三,回呼設計成函式傳入,讓呼叫端能各自決定成功後要做什麼,這是封裝能否通用的關鍵。