js操作cookie

cookie的作用

cookie最典型的应用是判断注册用户是否已经登录网站,用户可能会得到提示,是否在下一次进入此网站时保留用户信息以便简化登录手续。

还有一个重要作用是“购物车”之类处理。用户可能会在一段时间内在同一家网站的不同页面中选择不同的商品,这些信息都会写入cookie,以便在最后付款时提取信息。

js设置cookie

document.cookie="popped=yes"

js获取cookie

 1 function get_cookie(Name) {
 2    var search = Name + "="//查询检索的值
 3    var returnvalue = "";//返回值
 4    if (document.cookie.length > 0) {
 5      sd = document.cookie.indexOf(search);
 6      if (sd!= -1) {
 7         sd += search.length;
 8         end = document.cookie.indexOf(";", sd);
 9         if (end == -1)
10          end = document.cookie.length;
11          //unescape() 函数可对通过 escape() 编码的字符串进行解码。
12         returnvalue=unescape(document.cookie.substring(sd, end))
13       }
14    } 
15    return returnvalue;
16 }
17 //使用方式:
18 get_cookie("popped");

js删除cookie

可以将过期时间设定为一个过去的时间,例如:

1 //获取当前时间
2 var date=new Date();
3 //将date设置为过去的时间
4 date.setTime(date.getTime()-10000);
5 //将userId这个cookie删除
6 document.cookie="userId=828; expires="+date.toGMTString(); 

 

posted @ 2018-04-02 10:34  endlessmy  阅读(250)  评论(0编辑  收藏  举报