DIV CSS 佈局教程網

PJBlog 裡用到的 ajax.js:幾個實用的小函式
編輯:AJAX基礎知識     

部落格程式 PJBlog 內附的 ajax.js 很短,但每個函式都剛好解決一個實際問題。以下逐段拆解,這些寫法即使到今天也仍然值得一看。

簡化 DOM 操作的兩個小工具

function $(id) {
    return document.getElementById(id);
}

function echo(obj, html) {
    $(obj).innerHTML = html;
}

$ 這個單字元函式後來被 Prototype、jQuery 發揚光大,最早的靈感多半來自這類 blog 程式的實用主義: getElementById 打太長了。

顯示與隱藏

function fopen(obj)  { $(obj).style.display = ""; }
function fclose(obj) { $(obj).style.display = "none"; }

用來控制「載入中…」提示層的進出。實務上加上淡入淡出(transition: opacity .2s)會更柔和。

建立跨瀏覽器的 XMLHTTP 物件

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) {          // 設定 MIME 類別
            xmlhttp.overrideMimeType('text/xml');
        }
    }
    return xmlhttp;
}

這裡有個聰明的細節:先試 ActiveX、失敗才退回原生建構式。多數教程反過來寫,但先試 ActiveX 能在舊 IE 上拿到較穩定的 XML 支援。overrideMimeType('text/xml') 則是用來告訴瀏覽器「請以 XML 解析這份回應」,讓 responseXML 可用——這在伺服器沒送對 Content-Type 時特別有用。

取資料的主函式

function getdata(url, obj1, obj2) {
    var xmlhttp = createxmlhttp();
    if (!xmlhttp) {
        alert("您的瀏覽器不支援 XMLHTTP!!");
        return;
    }

    xmlhttp.onreadystatechange = requestdata;
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);

    function requestdata() {
        fopen(obj1);
        echo(obj1, "正在載入資料,請稍等......");

        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {
                if (obj1 != obj2) { fclose(obj1); }   // 提示層與內容層不同時,載完就收起提示
                echo(obj2, xmlhttp.responseText);
            }
        }
    }
}

這個設計有一個很實用的小巧思:傳入兩個容器 id。 obj1 是「載入中」提示要顯示的地方,obj2 是資料最終要填入的地方。當兩者相同(例如同一個 div 先顯示提示再換成內容)時就不收起;不同時才把提示層關掉。一個參數組解決了兩種常見版面需求。

另外注意 onreadystatechange 是掛在 open() 之前的——順序錯了就永遠不會觸發,這是最常被忽略的細節。

現代對照

用今天的語法,同樣的功能可以寫成:

async function getdata(url, loadingId, contentId) {
    const loading = document.getElementById(loadingId);
    const target  = document.getElementById(contentId);

    loading.style.display = "";
    loading.textContent = "正在載入資料,請稍候……";

    try {
        const response = await fetch(url);
        if (!response.ok) { throw new Error(response.status); }
        target.textContent = await response.text();   // 用 textContent 較安全
        if (loadingId !== contentId) { loading.style.display = "none"; }
    } catch (err) {
        loading.textContent = "載入失敗,請稍後再試";
    }
}

差異有三點值得注意:一是用 await 讓非同步程式碼讀起來像同步;二是用 response.ok 取代只判斷 status == 200;三是用 textContent 而非 innerHTML——若回傳內容可能含標籤字元,直接塞進 innerHTML 等於執行對方給的 HTML,是 XSS 的入口。這些觀念在 PJBlog 那個年代尚未普及,但現在是基本要求。

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