检索jQuery Cookie值

cig3rfwq  于 2023-08-04  发布在  jQuery
关注(0)|答案(4)|浏览(101)

例如,我有这个cookie:

$.cookie("foo", "500", { path: '/', expires: 365 });

字符串
如何获取该cookie的值并将其放入变量中?
例如(我知道这是不正确的):

var foo = $.cookie("foo").val();

waxmsbnn

waxmsbnn1#

只有var foo = $.cookie("foo")
不需要.val()调用,因为您没有访问DOM元素的 value

kx7yvsdv

kx7yvsdv2#

这对我很有效:

function getCookieValue(cname) { 
    // cname is the cookie name (foo) which value you are after
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.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 "";
}

字符串

uajslkp6

uajslkp63#

要获取cookie的值,您只需调用它的引用。举例来说:

$.cookie("foo", "somevalue");
alert($.cookie("foo"));

字符串
将发出警报:

somevalue

mnemlml8

mnemlml84#

通过这种方式我们可以访问
console.log($.cookie());//它将以对象的形式给出所有cookie
alert($.cookie('foo'));//它将给予cookie foo值即500

相关问题