简体   繁体   中英

Retrieve jQuery Cookie value

Example, I have this cookie:

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

How do I get the value of that cookie and put it into a variable?

For example (I know this is not correct):

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

It's just var foo = $.cookie("foo") .

There's no need for a .val() call as you're not accessing the value of a DOM element.

By this way we can access

console.log($.cookie()); //It will gives the all cookies in the form of object

alert($.cookie('foo')); //it will give cookie foo value ie 500

To get the value of a cookie, you can just call it's reference. For example:

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

Will alert:

somevalue

This worked for me

function getCookieValue(cname) { // cname is nothing but the cookie value which 
                                 //contains the value
                    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 "";
                    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM