在javascript中读取cookie值

时间:2014-09-30 10:23:51

标签: javascript asp.net-mvc-3 cookies

我正在我的代码中创建cookie,就像这样

            HttpCookie objCookie = new HttpCookie("DefaultName");
            objCookie.Expires = DateTime.Now.AddDays(5);
            objCookie.Values["Name"] = Name;
            objCookie.Values["Id"] = Id;
            Response.Cookies.Add(objCookie);

现在的问题是我如何才能访问价值观"名称"和" Id"在javascript函数?

2 个答案:

答案 0 :(得分:0)

下面的代码读取cookie中的内容

(function(){
    var cookies;

    function readCookie(name,c,C,i){
        if(cookies){ return cookies[name]; }

        c = document.cookie.split('; ');
        cookies = {};

        for(i=c.length-1; i>=0; i--){
           C = c[i].split('=');
           cookies[C[0]] = C[1];
        }

        return cookies[name];
    }

    window.readCookie = readCookie; // or expose it however you want
})();

答案 1 :(得分:0)

简单地说,var _value = document.cookie;

一般来说,如果你在cookies中有很多值,只需说它以逗号分隔,

var _cookiesArray = document.cookie.split(',');

使用jQuery

$(document).ready(function () {
var _value = $.cookie('Id'); //OR Name
alert(_value);