9.1 建立第一个 cookie

  • cookie 是具有特定格式的文本字符串;
  • cookieName=cookieValue; expires=expirationDateGMT;path=URLpath;domain=siteDomain;
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script>
        window.onload = nameFieldInit;
        function nameFieldInit() {
            var userName = "";
            if (document.cookie != "") {
                var cookieInfo = document.cookie.split("=");
                userName = cookieInfo[1];
            }
            document.getElementById("nameID").value = userName;
        }

        function setCookie() {
            var expireDate = new Date();
            expireDate.setMonth(expireDate.getMonth() + 6);
            var userName = document.getElementById("nameID").value;
            document.cookie = "cookieName=" + userName + ";expires=" + expireDate.toGMTString();
        }
    </script>
</head>
<body>
<p>JavaScript</p>
<form id="cookieForm" onsubmit="return setCookie()">
    <label>name:<input id="nameID" name="name"></label>
    <label>password:<input id="pwd" name="pwd"></label>
    <input type="submit" value="登录">
</form>
</body>
</html>