//AJAX request
function AJAX(method, url) {
this.method = method;
this.url = url;
AJAX.Counter++;
}
AJAX.Counter = 0;
AJAX.prototype.CreateXHR = function() { //create XMLHttpRequest
var xmlhttp_request = "";
try {
if (window.ActiveXObject) {
for (var i = 5; i; i--) {
try {
if (i == 2) {
xmlhttp_request = new ActiveXObject('Microsoft.XMLHTTP');
}
else {
xmlhttp_request = new ActiveXObject('Msxml2.XMLHTTP.' + i + '.0');
xmlhttp_request.setRequestHeader('Content-Type', 'text/xml');
xmlhttp_request.setRequestHeader('Charset', 'gb2312');
}
break;
}
catch (e) {
xmlhttp_request = false;
}
}
}
else if (window.XMLHttpRequest) {
xmlhttp_request = new XMLHttpRequest();
}
}
catch (e) { xmlhttp_request = false; }
return xmlhttp_request;
}
AJAX.prototype.EncodeURI = function(_url) {
var pos = _url.indexOf('?'),
http = '',
args = '';
if (pos != -1) {
http = _url.substring(0, pos + 1);
args = _url.substring(pos + 1);
var hash = args.split('&');
for (var i = 0; i < hash.length; i++) {
pos = hash[i].indexOf('=');
if (pos != -1) {
hash[i] = hash[i].substring(0, pos + 1) + encodeURIComponent(hash[i].substring(pos + 1));
}
}
}
else {
return _url;
}
return http + hash.join('&');
}
AJAX.prototype.CallAJAX = function(senderObjID) {
var xmlhttp_request = this.CreateXHR();
if (!xmlhttp_request) {
alert('您的瀏覽器不支援ajax。');
return;
}
if (this.method === 'GET') {
xmlhttp_request.open(this.method, this.EncodeURI(this.url), true);
xmlhttp_request.send(null);
var self = xmlhttp_request; //把引用賦給臨時變數self
var objID = senderObjID; //由哪個控制項觸發的
xmlhttp_request.onreadystatechange = function() {
thecallback(self,objID);
};
}
else {
throw new Error('AJAX還沒有實現非“GET”的傳遞方法。');
}
}
頁面端:
var ajax = new AJAX('GET', '../Handler/SelectDept.aspx?PARENT=01&temp=' + new Date().getMilliseconds());
ajax.CallAJAX(senderObjID);
......
function thecallback(xmlhttp_request, senderObjID) {
var result = xmlhttp_request.readyState;
switch (result) {
case 0:
case 1:
case 2:
case 3: break;
//這裡應該顯示一個彈窗提示使用者正在載入資料
......
case 4:
//getObj(senderObjID).removeAttribute('disabled');
//這裡應該刪除彈窗
if (xmlhttp_request.status == 200) {
//debugger;
//BindHandler(AJAX.Counter, senderObjID);為DOM綁定事件的方法
......
}
else {
alert('請求有錯誤。錯誤碼:' + xmlhttp_request.status);
return;
}
break;
default: alert('XMLHTTPRequest返回超出預期的值。');
break;
}
}