把 AJAX 常用操作抽象成一個獨立的 JS 文件(AJaxJS.JS),是提升開發效率的好習慣。這份代碼把加載提示、對象獲取、GET/POST 提交等封裝成通用函數,並配上詳盡註釋,讀取和發表評論都能直接複用。
// 顯示一個等待的窗口
document.write('<div id="loadingg" style="height:65px; width:205px; position:absolute; z-index:1000; border:3px #fff solid; text-align:center; font-size:12px; font-family:Arial; color:#660000; background:#222; opacity:.7; filter:alpha(opacity=70); display:none;"><br/><font color="#FF6600"><strong>數據正在讀取中,請等候...</strong></font><br/></div>');
// showloading 控制等待窗口的顯示和隱藏
function showloading() {
var obj = document.getElementById("loadingg");
if (obj.style.display != "") {
obj.style.left = ((document.documentElement.clientWidth - parseFloat(obj.style.width))/2) + document.documentElement.scrollLeft + "px";
obj.style.top = ((document.documentElement.clientHeight - parseFloat(obj.style.height))/2) + document.documentElement.scrollTop + "px";
obj.style.display = "";
} else { obj.style.display = "none"; }
}
// $() 取得指定 ID 的對象
function $(id) { return document.getElementById(id); }
// echo() 向指定對象 obj 顯示指定的 Html
function echo(obj, Html) { $(obj).innerHTML = Html; }
// fopen() 使指定的 obj 處於顯示狀態
function fopen(obj) { $(obj).style.display = ""; }
// fclose() 使指定的 obj 處於隱藏狀態
function fclose(obj) { $(obj).style.display = "none"; }
// createXMLhttp() 獲取 XMLHttpRequest 對象並返回
function createXMLhttp() {
var XMLhttp = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) {
try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { XMLhttp = false; }
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
if (XMLhttp.overrideMimeType) { xmlhttp.overrideMimeType('text/XML'); }
}
return XMLhttp;
}
// getdata() 獲取指定 URL 的數據並在 obj2 裡顯示,obj1 為提示信息
function getdata(url, obj1, obj2) {
var xmlhttp = createXMLhttp();
if (!XMLhttp) { alert("你的瀏覽器不支持XMLHTTP!!"); return; }
showloading()
XMLhttp.onreadystatechange = requestdata;
XMLhttp.open("GET", url, true);
XMLhttp.send(null);
function requestdata() {
fopen(obj1);
if (XMLhttp.readyState == 4) {
if (XMLhttp.status == 200) {
if (obj1 != obj2) { fclose(obj1); }
echo(obj2, XMLhttp.responseText);
showloading()
}
}
}
}
// postdata() 發送指定數據 data 到 url,並用 obj 顯示返回數據
function postdata(url, obj, data) {
var rnd = Math.random()
var xmlhttp = createXMLhttp();
if (!XMLhttp) { alert("你的瀏覽器不支持XMLHTTP!!"); return; }
showloading()
XMLhttp.open("POST", url, true);
XMLhttp.onreadystatechange = requestdata;
XMLhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
XMLhttp.send(data);
function requestdata() {
fopen(obj);
echo(obj,"正在提交數據,請稍等......");
if (XMLhttp.readyState == 4) {
if (XMLhttp.status == 200) {
echo(obj, XMLhttp.responseText);
reget(rnd);
setTimeout("echo('showresult','')",2000);
echo('Message','')
showloading()
}
}
}
}
// lTrim() 去掉字符串左邊的空格
function lTrim(str) {
if (str.charAt(0) == " ") { str = str.slice(1); str = lTrim(str); }
return str;
}
// rTrim() 去掉字符串右邊的空格
function rTrim(str) {
var iLength = str.length;
if (str.charAt(iLength - 1) == " ") { str = str.slice(0, iLength - 1); str = rTrim(str); }
return str;
}
// trim() 去掉字符串兩邊的空格
function trim(str) { return lTrim(rTrim(str)); }
// f() 只針對特定對象取值
function f(obj) { return trim(eval("document.Ajax_post."+obj+".value")); }
// SaveReply() 是表單的檢查提交函數
function SaveReply() {
if (f("username") == "") { alert("請填寫用戶名"); return false; }
if (f("Message") == "") { alert("內容不可為空"); return false; }
var validate, passWord, log_DisKey=0, log_DisURL=0, log_DisSM=0
validate = ""
passWord = ""
if (document.Ajax_post.log_DisKey.checked) { log_DisKey = f("log_DisKey") }
if (document.Ajax_post.log_DisURL.checked) { log_DisURL = f("log_DisURL") }
if (document.Ajax_post.log_DisSM.checked) { log_DisSM = f("log_DisSM") }
if ((typeof eval(document.Ajax_post.validate)) != "undefined") {
if (f("validate") == "") { alert("請填寫驗證碼"); return false; }
else { validate = f("validate"); }
}
if ((typeof eval(document.Ajax_post.passWord)) != "undefined") { password = f("passWord"); }
data = "username=" + escape(f("username")) + "&password=" + escape(passWord)
+ "&validate=" + escape(validate)
+ "&log_DisSM=" + escape(log_DisSM)
+ "&log_DisURL=" + escape(log_DisURL)
+ "&log_DisKey=" + escape(log_DisKey)
+ "&Message=" + escape(f("Message"))
+ "&logID=" + escape(f("logID"))
+ "&action=" + escape(f("action"));
postdata("wbc_blogcomm.ASP","showresult",data);
return true;
}
<div id="ShowComm"></div>
<script language="Javascript" type="text/Javascript" src="AJaxJS.JS"></script>
<script language="Javascript" type="text/Javascript">
function reget(str){
getdata('wbc_ShowComm.ASP?LogID=100&comDesc=Desc&DisComment=False&0.5675318&'+str,'ShowComm','ShowComm');
}
reget('get');
</script>
頁面加載時先調用 reget('get') 讀取評論列表;用戶提交後,SaveReply 收集並編碼表單數據,交給 postdata 異步提交,成功後再自動刷新評論。整個組件註釋清晰、職責分明,非常適合直接搬到自己的項目中複用。