设置Cookies

设置Cookies:

 public ActionResult Index()
        {
            //
            if (Request.Cookies["user"] != null)
            {
                //Server.HtmlEncode(Request.Cookies["user"]["username"].ToString());
                //Response.Cookies["username"].Value="gjy"; 
                Response.Cookies["user"]["username"] = "zq_byupdate";
                Response.Cookies["user"]["password"] = "123_byupdate";

            }
            else
            {
                HttpCookie cookie = new HttpCookie("user");
                cookie.Values["username"] = "zq";
                cookie.Values["password"] = "123";

                cookie.Expires = DateTime.Now.AddDays(30);
                Response.AppendCookie(cookie);
            }

            return View();
        }

 

读取Cookies:

 if (!IsPostBack)
            {
                string username;
                string password;

                if (Request.Cookies["user"] != null)
                {
                    username = Server.HtmlEncode(Request.Cookies["user"]["username"].ToString());
                    password = Server.HtmlEncode(Request.Cookies["user"]["password"].ToString());

                     //return Content(username + "&" + password);
                    this.Label1.Text = username;
                    this.Label2.Text = password;
                }
            }

 

JS获取Cookies:

方法一:

 function getCookie(name) {
            var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //正则匹配
            if (arr = document.cookie.match(reg)) {
                return unescape(arr[2]);
            }
            else {
                return null;
            }
        }

        $(function () {
            //
            var array = getCookie('user');
            if (array != null) {
                array = array.split('&');
                $("#t1").html(array[0]);
                $("#t2").html(array[1]);
            }
        })

方法二:

(function () {

            var temp = getCookie('user');
            alert(temp);

            //
            // GetAllCookies();

        })

        function getCookie(cookie_name) {
            var allcookies = document.cookie;
            var cookie_pos = allcookies.indexOf(cookie_name);   //索引的长度

            // 如果找到了索引,就代表cookie存在,
            // 反之,就说明不存在。
            if (cookie_pos != -1) {
                // 把cookie_pos放在值的开始,只要给值加1即可。
                cookie_pos += cookie_name.length + 1;      //这里容易出问题,所以请大家参考的时候自己好好研究一下
                var cookie_end = allcookies.indexOf(";", cookie_pos);

                if (cookie_end == -1) {
                    cookie_end = allcookies.length;
                }

                var value = unescape(allcookies.substring(cookie_pos, cookie_end));         //这里就可以得到你想要的cookie的值了。。。
            }
            return value;
        }

 

posted @ 2017-08-18 16:09  youguess  阅读(209)  评论(0编辑  收藏  举报