//--------------------------------------------------------------------------------------
//封裝XMLHTTP的Request類的代碼
var $ajax = new Object();
function getAjax() {
var ajax = false;
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
ajax = false;
}
}
if (!ajax && typeof XMLHttpRequest != 'undefined') {
ajax = new XMLHttpRequest();
}
return ajax;
}
//封裝XMLHTTP向伺服器發送請求的操作
$ajax.send = function (url, method, callback, data) {
var req = getAjax(); //得到一個XMLHTTP的執行個體
//當XMLHTTP的請求狀態發生改變時調用
req.onreadystatechange = function () {
// 當請求已經載入
if (req.readyState == 4) {
// 當請求返回成功
if (req.status == 200) {
// 當定義了成功回呼函數時,執行成功回呼函數
if (callback)
callback(req, data);
}
// 當請求返回錯誤
else {
alert("當載入資料時發生錯誤 :\n" + req.status + "/" + req.statusText);
}
try {
delete req;
req = null;
} catch (e) { }
}
}
//如果以POST方式回傳伺服器
if (method == "POST") {
req.open("POST", url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(data);
}
//以GET方式請求
else {
req.open("GET", url, true);
req.send(null);
}
}
//進一步封裝XMLHTTP以POST方式發送請求時的代碼
$ajax.sendPOST = function (url, data, callback) {
$ajax.send(url, "POST", callback, data);
}
//進一步封裝XMLHTTP以GET方式發送請求時的代碼
$ajax.sendGET = function (url, callback, args) {
return $ajax.send(url, "GET", callback, args);
}
//--------------------------------------------------------------------------------------
以上代碼很容易但是完成了ajax的基本需求用法也很簡單:
$ajax.sendPOST("Handler.ashx", "action=reply&" + parameter,
function (req, data) {
var rel=req.responseText;
}
);