getting or setting cookies with javascript

纵饮孤独 提交于 2019-12-13 02:44:28

问题


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


来源:https://stackoverflow.com/questions/860962/getting-or-setting-cookies-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!