简体   繁体   中英

How to put variable into cookie?

I'd like to put a variable's string into a cookie. (as the content) Currently the cookie does set and the name is username. (That part works) the content from the variable isnt saved in the cookie though. Here's what i have. I have looked at one other similar question and the answer didnt work. Possible because i'm using a string

var sharedContent = sharedURL;
var sharedURL = "http://www.example.com/";
function getUrl() {
window.location.href= sharedURL;
createCookie();
}
function createCookie() {
document.cookie = "username="+sharedContent+"; expires=Wed, 1 Jan 2025 13:47:11 UTC; path=/"
}

As you may have noticed, i am a bit new to using js.

Html:

<link href='https://fonts.googleapis.com/css?family=Lato:300' rel='stylesheet' type='text/css'>

<a href="https://www.minds.com/newsfeed"><div class="button" onclick="getUrl(); "><img src="icon.png" width="16">Share</div></a>

It is working perfectly fine if you change variable/function declaration position and changing ; to ,

var sharedURL = "http://www.example.com/";
var sharedContent = sharedURL;
function createCookie() {
var cookies = "username="+sharedContent+", expires=Wed, 1 Jan 2025 13:47:11 UTC, path=/"
document.cookie = cookies;
}
function getUrl() {
window.location.href= sharedURL;
createCookie();
}
getUrl();

Call CreaetCookie() function before window.location.href . I haven't try but it should work.

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