如何从用户输入中获取cookie,并将其显示在html元素上

How do I get a cookie from user input, and display it on an html element

本文关键字:显示 html 元素 用户 输入 cookie 获取      更新时间:2023-09-26

我正在制作一个使用cookie获取用户名的网站。当我试图用inner.html显示它时,它甚至不会提示用户。这是我的密码。区域是特定的函数checkCookie()

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function setCookie(cname,cvalue,exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires=" + d.toGMTString();
        document.cookie = cname+"="+cvalue+"; "+expires;
    }
    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1);
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
    function checkCookie() {
        var user=getCookie("username");
         if (user != null) {
            document.getElementById("person").innerHTML =
            "Hello " + user + "!";
        } else {
           user = prompt("Please enter your name:","");
           if (user != "" && user != null) {
               setCookie("username", user, 30);
           }
        }
    }
    </script>
    </head>
    <body onload="checkCookie()">
    <p id="person">anonymous user</p>
    </body>
    </html>

更改

return "";

至:

return null;

checkCookie期望getCookie在未找到cookie时返回null。空字符串与null不同。

演示