简体   繁体   中英

How to retrieve a cookie's value?

I may be asking the wrong question but I am still fairly new to JavaScript. I need to create a cookie that will re-strict the number of usages a user has for an online product demo. In pseudo code, I assume it would be something like this:

if(readCookie('demo') == null){ 
 createCookie('demo','1',1);}  //Assuming the functions for setting a cookie and retrieving it have already been created.
else {
    readCookie('demo');
}

if demo cookie has value{
    increment the value by one
}
else if value exceeds 10 {
    alert message //I set this so I could test out the function
}

Any help would be appreciated!

This page will tell you everything you need to know and even provides example functions for you to plug into your own code to make cookie handling very easy.

http://www.quirksmode.org/js/cookies.html

If your open to using jQuery, you should look at the jquery.cookie plugin.

Examples (via Documentation):

Create session cookie:

$.cookie('the_cookie', 'the_value');

Create expiring cookie, 7 days from then:

$.cookie('the_cookie', 'the_value', { expires: 7 });

Create expiring cookie, valid across entire page:

$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

Read cookie:

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

Delete cookie by passing null as value:

$.cookie

As noted by a user-comment, a cookie is not a good way to do this. You cannot enforce it.

That said, I wrote and maintain a JavaScript cookie API. Check it out at: http://code.google.com/p/cookies/ (It does NOT require jQuery, although it has extras built in if jQ is present).

Here is your pseudo code translated to use the lib: http://jsfiddle.net/JAAulde/BGFQs/ (You'll see the alert after clicking "Run" enough times)

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