DIV CSS 佈局教程網

用 cookie 記住訪客名字:張三李四都歡迎回來
編輯:關於JavaScript     

這是一個很經典的 cookie 入門練習:使用者第一次來訪時詢問暱稱並寫入 cookie;下次再來時讀出來,直接問候。它涵蓋了 cookie 讀、寫、設過期三個基本動作。

範例

<!DOCTYPE html>
<html>
<head>
<script>
function getCookie(c_name) {
    var c_value = document.cookie;
    var c_start = c_value.indexOf(" " + c_name + "=");

    if (c_start == -1) {
        c_start = c_value.indexOf(c_name + "=");
    }
    if (c_start == -1) {
        c_value = null;
    } else {
        c_start = c_value.indexOf("=", c_start) + 1;
        var c_end = c_value.indexOf(";", c_start);
        if (c_end == -1) {
            c_end = c_value.length;
        }
        c_value = unescape(c_value.substring(c_start, c_end));
    }
    return c_value;
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function checkCookie() {
    var username = getCookie("username");
    if (username != null && username != "") {
        alert("Welcome again " + username);
    } else {
        username = prompt("Please enter your name:", "");
        if (username != null && username != "") {
            setCookie("username", username, 365);
        }
    }
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>

拆解三個關鍵

為什麼 document.cookie 那麼難讀?因為它不是物件,而是一個單一字串,所有 cookie 都被分號串在一起,像 "a=1; username=John; theme=dark"。所以 getCookie 必須自己切字串——先找 " name=",找不到再找開頭的 "name="(處理第一個 cookie 沒有前導空格的情況),最後切到分號或字串結尾。

為什麼要 escape/unescape?因為 cookie 的值不能含分號、逗號、空白等字元,必須先編碼。這兩個函式已被標記為不建議使用,現代請改用 encodeURIComponent() 與 decodeURIComponent()。

不設 expires 會怎樣?會變成 session cookie,瀏覽器關掉就没了。範例設 365 天是為了讓它長期保留。

現代做法

今天處理 cookie 有兩個更好的選擇。一是用 document.cookie 的簡化寫法搭配 SameSite;二是直接用 localStorage(純前端資料)或 sessionStorage:

localStorage.setItem("username", "John");
localStorage.getItem("username");

差別在於:cookie 會隨每次請求自動送往伺服器,適合 session、身分驗證;localStorage 純存在瀏覽器,容量更大,適合非敏感的前端狀態。使用者暱稱這種資料放 localStorage 更合適,也不必有 escape 的困擾。

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