getting or setting cookies with javascript

2019-08-27 17:18发布

问题:

My question is if I can set a cookie using javascript (and read it)

My first impression is that the code beneath doesn't work If I look in my vista cookie folder, I can not see the name of the cookie

function zetCookie(naam,waarde,dagen) {     // setCookie(name,value,days)
    if (dagen) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var verloopdatum = "; expires="+date.toGMTString(); // expiry_date
    }
    else var verloopdatum = "";
    document.cookie = naam+"="+waarde+verloopdatum+"; path=/";
}    

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;
}

回答1:

I can't answer why the cookie is not showing in your Vista folder, but that code properly sets and reads cookies as intended. How are you testing it? An easier way to test whether the cookies are sticking is by simply doing something like this:

<input type="button" value="Set" onClick="createCookie('test','yay',5);">
<input type="button" value="Read" onClick="alert(readCookie('test'));">

You can refresh the page between Setting and Reading it if makes you feel better, but it works for me.

If that doesn't show what you're expecting, make sure your browser is setup to accept cookies. :)

EDIT: Looking at your code, you missed replacing days in this line:

date.setTime(date.getTime()+(days*24*60*60*1000));


回答2:

I'm testing it here: http://flamencopeko.net/cookie.php and here: http://flamencopeko.net/cookie.js. Works perfect.

And, yeah, Firebug's Cookies panel is great.

I'm trying to use your script to save font size preference. Here is a thread on that: simplify font size toggle.



回答3:

  1. Install Firefox
  2. Install FireBug
  3. Install FireCookies
  4. Download JQuery
  5. Download the Cookie plugin