javaScript--7 cookies设置与获取

 

 

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Cookies</title>
</head>

<head>
  <script>
    // 设置cookie
    function setCookie(cname, cvalue, exdays) {
      var d = new Date();
      d.setTime(d.getTime() + (exdays * 1000));
      var expires = "expires=" + d.toGMTString();
      document.cookie = cname + "=" + cvalue + "; " + expires;
    }

    //添加Cookie
    function addCookie() {
      var cookieName = document.getElementById("setCookie").value;
      var cookieValue = document.getElementById("param").value;
      var cookieEx = document.getElementById("time").value;
      setCookie(cookieName, cookieValue, cookieEx);
    }

    // 获取cookies
    function getCookie(cname) {
      var name = cname + "=";
      var ca = document.cookie.split(';');
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) {
          return c.substring(name.length, c.length);
        }
      }
      return "无数据";
    }

    //查询Cookie
    function loadCookie() {
      var cookieName = document.getElementById("getCookie").value;
      var cookieValue = getCookie(cookieName);
      document.getElementById("spnCookies").innerText = cookieValue;
      console.log(cookieName + "====" + cookieValue);
    }
  </script>
</head>

<body>
  设置cookies:<br />
  名称:<input type="text" id="setCookie" /> 参数:<input type="text" id="param" /> 有效时间:<input type="number" id="time">
  <input type="button" value="添加Cookie" onclick="addCookie()" /><br>

  获取cookies:<br />
  名称:<input type="text" id="getCookie" /> <span id="spnCookies"></span><br>
  <input type="button" value="获取Cookie"
    onclick="loadCookie()" />
</body>

</html>

 

posted @ 2022-10-03 13:33  怪圣卡杰  阅读(43)  评论(0编辑  收藏  举报