简体   繁体   中英

Getting value from a cookie

I have set a cookie using the following and it works well. I can see it in browser cookie(console).

But how can i get back the value from cookie ??

days = 1;
cookiename = 'uid';
cookieValue = result.pp.uid;                        
if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
}else var expires = "";
document.cookie = cookiename + "=" + cookieValue + expires + "; path=/";

I have the following code , but i dont want to use the function.

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

Ive no idea of how they are getting the value of cookie..

Is there a simple way like document.cookie ?

Try this library

https://github.com/carhartl/jquery-cookie

Also see this SO post How do I set/unset cookie with jQuery?

Example from their docs

Read cookie:

$.cookie('the_cookie'); // => "the_value"
$.cookie('not_existing'); // => undefined

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