cookie的应用

### 封装一个存取cookie的方法

setCookie: function (cname, cvalue, exdays) {
    let d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    let expires = "expires=" + d.toUTCString();
    let domain = ""
    domain = ";domain=.xxxx.com.cn"
    document.cookie = cname + "=" + cvalue + ";" + expires + domain + ";path=/";
  },

  getCookie: function (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 "";
  }

调用cookie进行存取

cookie.setCookie("key", "vaule", 3000); //存入cookie,这里设置的过期时间为3000天

cookie.getCookie('key') //读取cookie中key对应的value

 632 total views,  2 views today

Revisions

Comments are closed.