【问题标题】:How to write a cookie to remember a username in JavaScript如何编写 cookie 来记住 JavaScript 中的用户名
【发布时间】:2013-05-19 14:09:07
【问题描述】:

我正在开发一个项目的登录页面,我想知道如何设置一个 cookie 来记住用户名

【问题讨论】:

    标签: javascript html authentication cookies


    【解决方案1】:

    这里是示例代码。用于 html 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 username:","");
      if (username!=null && username!="")
        {
        setCookie("username",username,365);
        }
      }
    }
    </script>
    </head>
    <body onload="checkCookie()">
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2012-08-03
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      相关资源
      最近更新 更多