cookie的一些操作

1、JS加cookie

let exdate = new Date() // 获取时间
exdate.setTime(exdate.getTime() + 60 * 5 * 1000) //保存的天数
window.document.cookie = 'LiXiangLvSuoID=' + row.Fid + ';path=/;expires=' + exdate.toGMTString();

2、JS获取cookie

 function getCook (key) {
                if (document.cookie.length > 0) {
                    var arr = document.cookie.split('; ') // 这里显示的格式需要切割一下自己可输出看下
                    for (let i = 0; i < arr.length; i++) {
                        let arr2 = arr[i].split('=') // 再次切割
                        // 判断查找相对应的值
                        if (arr2[0] === key) {
                            return arr2[1]
                        }
                    }
                }
            }

3、后台cookie

//第一种添加Cookie方法
        HttpCookie myCookie = new HttpCookie("userrole");
        myCookie.Values["a"] = "a";
        myCookie.Values[""] = "b";
        myCookie.Expires.AddDays(1);
        Response.Cookies.Add(myCookie);
        //Response.AppendCookie(mycookie);这个也可以添加
        //第一种获取Cookie方法
        Response.Write(Request.Cookies["userrole"].Values["a"].ToString());
        //第二种添加Cookie方法
        HttpCookie myCookie = new HttpCookie("userrole");
        myCookie.Values["a"] = "a";
        myCookie.Values["b"] = "b";
        myCookie.Expires.AddDays(1);
        Response.Cookies.Add(myCookie);
        //第二种读取Cookie方法
        HttpCookie cookie = Request.Cookies["userrole"];
        Response.Write(cookie.Values["a"].ToString());
        Response.Write(cookie.Values["b"].ToString());

        //第三种添加Cookie方法
        HttpCookie myCookie = new HttpCookie("userrole");
        myCookie.Value = "a";
        Response.Cookies.Add(myCookie);
        //第三种读取Cookie方法
        Response.Write(Request.Cookies["userrole"].Value);

        //第四种添加Cookie方法
        HttpContext.Current.Response.Cookies.Add(new HttpCookie("userrole", "超级管理员"));
        Response.Cookies["userrole"].Value = "超级管理员";
        HttpCookie cookie = Request.Cookies["userrole"];
        Response.Write(cookie.Value);
        //第三种读取Cookie方法
        Response.Write(Request.Cookies["userrole"].Value);

  

posted @ 2022-06-08 09:45  若白过隙  阅读(19)  评论(0编辑  收藏  举报