Get cookie by name

2018-12-31 10:14发布

I have a getter to get the value from a cookie.

Now I have 2 cookies by the name shares= and by the name obligations= .

I want to make this getter only to get the values from the obligations cookie.

How do I do this? So the 'for' splits the data into separate values and puts it in an array.

 function getCookie1() {
// What do I have to add here to look only in the "obligations=" cookie? 
// Because now it searches all the cookies.

    var elements = document.cookie.split('=');
    var obligations= elements[1].split('%');
    for (var i = 0; i < obligations.length - 1; i++) {
        var tmp = obligations[i].split('$');
        addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);
    }
 }

30条回答
残风、尘缘若梦
2楼-- · 2018-12-31 10:54

My solution is this:

function getCookieValue(cookieName) {
    var ca = document.cookie.split('; ');
    return _.find(ca, function (cookie) {
        return cookie.indexOf(cookieName) === 0;
    });
}

This function uses the Underscorejs _.find-function. Returns undefined if cookie name doesn't exist

查看更多
骚的不知所云
3楼-- · 2018-12-31 10:54

Just to add an "official" answer to this response, I'm copy/pasting the solution to set and retrieve cookies from MDN (here's the JSfiddle

    document.cookie = "test1=Hello";
    document.cookie = "test2=World";

    var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");

    function alertCookieValue() {
      alert(cookieValue);
    }

In you particular case, you would use the following function

    function getCookieValue() {
      return document.cookie.replace(/(?:(?:^|.*;\s*)obligations\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    }

Note that i only replaced "test2" from the example, with "obligations".

查看更多
何处买醉
4楼-- · 2018-12-31 10:56

always works well:

function getCookie(cname) {
    var name = cname + "=",
        ca = document.cookie.split(';'),
        i,
        c,
        ca_length = ca.length;
    for (i = 0; i < ca_length; i += 1) {
        c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) !== -1) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function setCookie(variable, value, expires_seconds) {
    var d = new Date();
    d = new Date(d.getTime() + 1000 * expires_seconds);
    document.cookie = variable + '=' + value + '; expires=' + d.toGMTString() + ';';
}

No requirements for jQuery or anything. Pure old good JavaScript.

查看更多
零度萤火
5楼-- · 2018-12-31 10:56

If you just need to check if some cookie exist then simple do this:

document.cookie.split('logged=true').length == 2

if cookie logged=true exist, you will get 2, if not 1.

logged=true - change this to you cookie name=value, or just a name

查看更多
听够珍惜
6楼-- · 2018-12-31 10:57

I know it is an old question but I came across this problem too. Just for the record, There is a little API in developers mozilla web page.

Yoy can get any cookie by name using only JS. The code is also cleaner IMHO (except for the long line, that I'm sure you can easily fix).

function getCookie(sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
}

As stated in the comments be aware that this method assumes that the key and value were encoded using encodeURIComponent(). Remove decode & encodeURIComponent() if the key and value of the cookie were not encoded.

查看更多
余欢
7楼-- · 2018-12-31 10:58

I have done it this way. so that i get an object to access to separate the values.With this u can pass the cookie to the parent and then you can access your values by the keys like

var cookies=getCookieVal(mycookie);
alert(cookies.mykey);
function getCookieVal(parent) {
            var cookievalue = $.cookie(parent).split('&');
            var obj = {};
            $.each(cookievalue, function (i, v) {
                var key = v.substr(0, v.indexOf("="));
                var val = v.substr(v.indexOf("=") + 1, v.length);

                obj[key] = val;

            });
            return obj;
        }  
查看更多
登录 后发表回答