DIV CSS 佈局教程網

點擊不同連結,讓 Ajax 回傳內容顯示在固定的 div 裡
編輯:AJAX基礎知識     

很多時候我們希望點擊某個連結時,不要換頁,而是把內容載入到頁面上某個固定區域。這其實是 Ajax 最經典的用途之一。以下是一個可直接運作的完整範例。

<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script language="javascript">
var http_request = false;

function createRequest(url, objID) {
    http_request = false;

    if (window.XMLHttpRequest) {
        // 非 IE 瀏覽器
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType("text/xml");
        }
    } else if (window.ActiveXObject) {
        // IE 瀏覽器
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        alert("無法建立 XMLHTTP 實例");
        return false;
    }

    http_request.open("GET", url, true);
    http_request.send(null);

    var obj = document.getElementById(objID);

    http_request.onreadystatechange = function () {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                obj.innerHTML = http_request.responseText;
            } else {
                alert('您請求的頁面發現錯誤!');
            }
        }
    };
}
</script>
</head>

<body onload="createRequest('content1.html','show')">
<div align="center">
<a href="content1.html"
   onclick="createRequest('content1.html','show');return false;">no1</a> |
<a href="content2.html"
   onclick="createRequest('content2.html','show');return false;">no2</a> |
<a href="content3.html"
   onclick="createRequest('content3.html','show');return false;">no3</a>
</div>

<div id="show" align="center"></div>
</body>
</html>

幾個關鍵設計

onclick 最後的 return false。這一項不可省略。少了它,瀏覽器會照著 href 去換頁,Ajax 抓回的內容就白做了。保留 href 則是為了讓 JavaScript 被停用時,連結仍能正常跳轉——這是一種「漸進增強」的寫法。

把目標容器 id 當參數傳入。函式設計成 createRequest(url, objID),而不是寫死 getElementById('show')。這樣同一個函式就能服務頁面上任何多個載入區,不必複製程式碼。

onload 時先載入預設內容。<body onload="createRequest('content1.html','show')"> 讓頁面一打開就有內容,避免出現空白區。

onreadystatechange 要設在 send 之前。範例中設在 send() 之後,實務上建議移到 open() 與 send() 之間,確保不會漏掉任何狀態變更。

可以再強化的地方

目前每次點擊都會重新抓一次,若內容不常變,可以簡單快取已載入的頁面避免重複請求。另外,載入過程中可以先把容器設為「載入中…」,讓使用者知道正在發生什麼;請求較慢時,這個提示會明顯改善感受。

最後,若三個面板的內容彼此有關(例如同一頁的分頁),也可以用 this.href 直接取值,讓 onclick 只寫 return loadInto(this.href, 'show'),程式碼會更短。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved