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:49

set by javascript

document.cookie = 'cookiename=tesing';

get by jquery with the jquery-cookie plugin

var value = $.cookie("cookiename");

alert(value);
查看更多
笑指拈花
3楼-- · 2018-12-31 10:51

If you use jQuery I recommend you to use this plugin:

https://github.com/carhartl/jquery-cookie
https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js

<script type="text/javascript"
 src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js">

So you can read cookie like this:

var value = $.cookie("obligations");

Also you can write cookie:

$.cookie('obligations', 'new_value');
$.cookie('obligations', 'new_value', { expires: 14, path: '/' });

Delete cookie:

$.removeCookie('obligations');
查看更多
低头抚发
4楼-- · 2018-12-31 10:52

One approach, which avoids iterating over an array, would be:

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

Walkthrough

Splitting a string by token will produce either, an array with one string (same value), in case token does not exist in a string, or an array with two strings , in case token is found in a string .

The first (left) element is string of what was before the token, and the second one (right) is what is string of what was after the token.

(NOTE: in case string starts with a token, first element is an empty string)

Considering that cookies are stored as follows:

"{name}={value}; {name}={value}; ..."

in order to retrieve specific cookie value, we just need to get string that is after "; {name}=" and before next ";". Before we do any processing, we prepend the cookies string with "; ", so that every cookie name, including the first one, is enclosed with "; " and "=":

"; {name}={value}; {name}={value}; ..."

Now, we can first split by "; {name}=", and if token is found in a cookie string (i.e. we have two elements), we will end up with second element being a string that begins with our cookie value. Then we pull that out from an array (i.e. pop), and repeat the same process, but now with ";" as a token, but this time pulling out the left string (i.e. shift) to get the actual token value.

查看更多
爱死公子算了
5楼-- · 2018-12-31 10:52

Here is a pretty short version

 function getCookie(n) {
    let a = `; ${document.cookie}`.match(`;\\s*${n}=([^;]+)`);
    return a ? a[1] : '';
}

Note that I made use of ES6's template strings to compose the regex expression.

查看更多
千与千寻千般痛.
6楼-- · 2018-12-31 10:52

reference: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

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

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

  alert(cookieValue);
查看更多
几人难应
7楼-- · 2018-12-31 10:53

Use object.defineProperty

With this, you can easily access cookies

Object.defineProperty(window, "Cookies", {
    get: function() {
        return document.cookie.split(';').reduce(function(cookies, cookie) {
            cookies[cookie.split("=")[0]] = unescape(cookie.split("=")[1]);
            return cookies
        }, {});
    }
});

From now on you can just do:

alert( Cookies.obligations );

This will automatically update too, so if you change a cookie, the Cookies will change too.

查看更多
登录 后发表回答