【问题标题】:Javascript - Set a Browser CookieJavascript - 设置浏览器 Cookie
【发布时间】:2020-06-06 22:12:33
【问题描述】:

当用户点击一个按钮时,它会将他们带到一个链接,但在他们转到该链接之前,cookie 需要设置为英语 (EN) 或法语 (FR)。我在这里举了一个例子: http://www.quirksmode.org/js/cookies.html

但由于某种原因,它没有在 cookie 中读取,我不确定我哪里出错了。 这就是我所拥有的:

<!DOCTYPE html>
<html>
<body>

<p>This is for the Browser Cookies.</p>

<button onclick="EN_Cookie()">English Link</button>  <button onclick="FR_Cookie()">French Link</button>


<script>
function EN_Cookie() {  
    setCookie("SMDCookie","EN",7);
    //location.href = 'https://google.com';
}

function FR_Cookie() {
   setCookie("SMDCookie","FR",7);
   //location.href = 'https://google.com';
}

function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

</script>

</body>
</html>

有什么建议吗??

【问题讨论】:

  • “它没有读取 cookie”是什么意思?
  • 你在哪里读取cookie?在本地运行document.cookie.split(';').filter(x =&gt; x.includes('SMDCookie'))说明cookie设置功能有效。

标签: javascript html cookies


【解决方案1】:

我查看了您的代码,发现您设置的 cookie 功能是正确的。 可能是你的getCookie不起作用,我分享的是get cookie功能:

  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 "";
 }

【讨论】:

    【解决方案2】:

    以下是可用于创建和检索 Cookie 的函数

    function createCookie(name, value, days) {
        var expires;
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        }
        else {
            expires = "";
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    }
    
    function getCookie(c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) {
                    c_end = document.cookie.length;
                }
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
    }
    

    参考 - How do I create and read a value from cookie?

    【讨论】:

      猜你喜欢
      • 2014-05-07
      • 2014-08-10
      • 2018-10-26
      • 2017-12-17
      • 2013-08-07
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      相关资源
      最近更新 更多