检索jQuery Cookie值

dar*_*ryl 14 javascript cookies jquery

例如,我有这个cookie:

$.cookie("foo", "500", { path: '/', expires: 365 });
Run Code Online (Sandbox Code Playgroud)

如何获取该cookie的值并将其放入变量中?

例如(我知道这不正确):

var foo = $.cookie("foo").val();
Run Code Online (Sandbox Code Playgroud)

Mat*_*all 18

这只是var foo = $.cookie("foo").

.val()由于您没有访问DOM元素的,因此无需调用.


Ank*_*ngh 5

这对我有用:

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 "";
}
Run Code Online (Sandbox Code Playgroud)