简体   繁体   中英

javascript how to set and retrieve a cookie simple

I have been looking at some sites about js cookies such as:

http://www.w3schools.com/js/js_cookies.asp
http://www.quirksmode.org/js/cookies.html Cannot list more links because of reputation.

I could not find anymore useful websites. The ones above don't work for me or are too complicated. I have found the quirksmode website useful but it didn't work. Here's the code I made to test it:

<html>
<head>
<script>
function read() {
    var x = readCookie('scon')
    if (x) {
        alert(x);
    }
}

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

function createCookie() {
    document.cookie = 'scon=testcookie; expires=Thu, 17 Jan 2013 13:47:11 UTC; path=/'
}   


</script>
    <title>Page Title</title>
</head>
<body>
<button onclick="createCookie()">Create</button>
<button onclick="read()">Read</button>

</body>
</html>

Please can you see whats going wrong and try to explain why and which bit does what if possible. This is going to be used as a standard cookie to save a setting.

What website browser are you using?

If you are using Firefox then it should just work, but Chrome and maybe others don't support "local" cookies... meaning that you have to run the JavaScript on an actual local server or on an actual web host.

Try running your code in the latest Firefox... it worked for me.

Hope that makes sense

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