简体   繁体   中英

Setting, Reading and Writing Cookie with JavaScript

In this example I am to ask the user for their name via a prompt, then use the cookie to write to a div, "Welcome, savedCookie!" after entering and then each time they visit the page before the expiration.

I get the browser to present a prompt asking for my name and then it writes to the div as "Welcome, undefined!" I can't figure out why I receive the error.

 //Setting cookie for Users Name function set_it() { var userName = prompt("Please Enter Your Name", ""), thetext = "name=" + userName, expdate = ";expires=Mon, 27 Mar 2017 13:00:00 UTC", newtext = encodeURIComponent(thetext); newtext += expdate; document.cookie = newtext; } //Reading & Writing cookie function read_it() { var rawCookie = document.cookie; bakedCookie = decodeURIComponent(rawCookie); yumCookie = bakedCookie.split("="); document.getElementById("greeting").innerHTML = "<p>Welcome, " + yumCookie[1] + "!</p>"; } if (document.cookie) { read_it(); } else { set_it(); read_it(); } 
 <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <div id="greeting"> <script src="prjs13_2.js"></script> </div> </body> </html> 

Try to run your only this code in console and look what you get-

 var userName = prompt("Please Enter Your Name", ""),
      thetext = "name=" + userName,
      expdate = ";expires=Mon, 27 Mar 2017 13:00:00 UTC",
      newtext = encodeURIComponent(thetext);
    newtext += expdate;
    document.cookie = newtext;

I did it for the name "david" and i got this-

name%3Ddavid;expires=Mon, 27 Mar 2017 13:00:00 UTC"

when you are setting your cookie your name attribute is not valid. try this code instead (without encodeURIComponent and ; instead of comma)-

var userName = prompt("Please Enter Your Name", "");
var  thetext = "name=" + userName;
var expdate = ";expires=Mon, 27 Mar 2017 13:00:00 UTC";
var newtext = thetext;
document.cookie = newtext;

You can use following function to get/set cookies:

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    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);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function checkCookie() {
    var user = getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
        user = prompt("Please enter your name:", "");
        if (user != "" && user != null) {
            setCookie("username", user, 365);
        }
    }
}

Here is some fiddle example: fiddle

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