這份範例示範如何用 Ajax 打造標籤式(Tab)導航:點擊不同的標籤,就透過非同步請求抓回對應的內容注入頁面,全程不刷新。整個實作由三部分組成——JavaScript 邏輯(function.JS)、樣式表(style.CSS)與頁面結構(HTML)。
先是一支跨瀏覽器抓取 DOM 元素的小工具 getObject(),依序嘗試 W3C DOM、IE4 DOM 與 NN4 DOM 三種寫法,找不到就回傳 false:
<!--
function getObject(objectId) {
if(document.getElementById && document.getElementById(objectId)) {
return document.getElementById(objectId);
}
else if (document.all && document.all(objectId)) {
return document.all(objectId);
}
else if (document.layers && document.layers[objectId]) {
return document.layers[objectId];
}
else {
return false;
}
}
接著宣告幾個全域變數,並寫出建立 XMLHttpRequest 物件的函式,同時兼顧 Mozilla 原生物件與 IE 的 ActiveX 版本,連建立失敗都準備好提示訊息:
var responsecont;
var XMLHttp;
var requestType;
var newsstring;
function CreateXMLHttpRequest(){
if (window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP.3.0");
}
catch (e){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){newsstring = "服務器繁忙,請稍後重新連接!";}
}
}
}
核心的 getnews() 依標籤 id 與序號拼出要抓取的靜態檔名,以 GET 方式送出請求,並刻意把 If-Modified-Since 設為 0,避開快取問題:
function getnews(tagid,x){
var url = tagid+'_'+x+'.htm';
requestType = tagid;
CreateXMLHttpRequest();
XMLHttp.onreadystatechange = processRequestChange;
XMLHttp.open("GET", url, true);
XMLHttp.setRequestHeader("If-Modified-Since","0");
XMLHttp.send(null);
}
processRequestChange() 負責在 readyState 為 4(完成)且狀態碼為 200 時,把回應文字取出並注入對應容器:
function processRequestChange(){
if (XMLHttp.readyState == 4){
if (window.location.href.indexOf("http")==-1 || XMLHttp.status == 200){
newsstring = XMLHttp.responseText;
shownews(requestType,newsstring);
}
}
}
shownews() 把內容寫進目標元素;TabNews() 則是切換樣式的關鍵,它遍歷各標籤,切換 active 樣式、控制顯示與隱藏,並觸發對應的 getnews():
function shownews(requestType,newsstring){
responsecont = getObject(requestType+'_cnt');
responsecont.innerHTML = newsstring;
}
function TabNews(tagid,x){
for (var i=1;i<=7;i+=2) {
if (i == x) {
getObject(tagid+i).className="tabactive"+i;
if(i!=1){
getObject(tagid+(i-1)).style.display="none";
if(i!=7){
getObject(tagid+(i+1)).style.display="none";
}
}
if(i==1){
getObject(tagid+"2").style.display="none";
}
try{
getnews(tagid,i);
}
catch(e){
alert(e);
}
}
else {
getObject(tagid+i).className="";
if(i!=7){
getObject(tagid+(i+1)).style.display="block";
}
}
}
}
//-->
樣式表負責整體版面與配色,包含連結樣式、清除浮動、間距、字體顏色,以及標籤導航與內容區的樣式。以下保留關鍵片段:
body{ margin: 0;padding: 0;background: #FFF;color: #000;font: normal 12px 宋體,arial,sans-serif;text-align: left;}
div,form,ul,ol,li,span,p {border: 0;margin: 0;padding: 0;}
/*鏈接樣式*/
a:link{color: #000;text-decoration: none;}
a:visited{color: #000;text-decoration: none;}
a:hover{color: #16387C;text-decoration: underline;}
/*清除float*/
.clear{ clear: both; font-size:1px; visibility: hidden; }
/*新聞標簽導航*/
.news_tabsnav{
background: url(../images/tab_bg.gif) #FFF left top repeat-x;
border: solid #B0BEC7;
border-width: 0 1px 0 1px;
height: 22px;
margin: 0 auto;
padding: 0;
width: 506px;
}
/*導航菜單點擊後的樣式*/
.news_tabsnav .tabactive1{
background: url(../images/tab_active1.gif);
color: #F26400;
font: bold 12px 宋體,arial,sans-serif;
height: 18px;
text-align: center;
width: 120px;
}
/*最新消息主體*/
.news_content{
border: solid #B0BEC7;
border-width: 0 1px 1px 1px;
margin: 0 auto;
width: 506px;
}
頁面用兩組標籤導航示範:一組是「推薦/折扣/團購/活動」資訊,另一組是「華夏資訊/動感寶貝/動漫世界/體育世界」。每個標籤都是帶 id 的 li,內容容器則用對應的 id(如 tab1 對應 tab1_cnt)供 Ajax 注入。以下為精簡後的骨架:
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script language="Javascript" type="text/javascript" src="js/function.JS"></script>
<div class="news_tabsnav">
<ul class="tabsmenu">
<li class="tabactive1" style="cursor:pointer" id="tab1">推薦信息</li>
<li style="cursor:pointer" id="tab3">最新折扣信息</li>
<li style="cursor:pointer" id="tab5">最新團購信息</li>
<li style="cursor:pointer" id="tab7">最新活動信息</li>
</ul>
</div>
<div class="news_content">
<div id="tab_cnt">
<div class="news_list">
<img src="https://www.pushad.com/Info/images/gyy.jpg" alt="推薦圖片新聞" width="154" height="115" border="0" />
<ul class="new_top7">
<li><a href="#">範例新聞標題</a> 2006-08-15</li>
</ul>
</div>
</div>
</div>
整組範例的運作邏輯是:使用者點擊某個標籤 → TabNews() 切換 active 樣式並顯示/隱藏對應區塊 → getnews() 非同步抓回靜態 htm 檔 → 回應完成後由 shownews() 注入到內容容器。由於內容是動態載入的,切換標籤時頁面不會整頁刷新,正是 Ajax 標籤導航的精髓所在。