简体   繁体   English

JavaScript保存Cookie

[英]JavaScript Save Cookies

I am following a tutorial for cookies and in the tutorial you enter your name, and you can refresh then display your name, so the name is actually saved as a cookie. 我正在关注Cookie的教程,在该教程中输入名称,然后可以刷新然后显示您的名称,因此该名称实际上被保存为Cookie。 However when I am trying this in a personal file, the cookie is not being saved if I refresh the page, I can only see the cookie once per session, so how do I save the cookie for as many sessions as I want? 但是,当我尝试在个人文件中执行此操作时,如果刷新页面,则不会保存cookie,每个会话只能看到一次cookie,那么如何为所需的会话保存cookie?

I suppose you can't use cookies in a snippet, but if you can help, copy and paste this into a personal file. 我想您不能在代码段中使用Cookie ,但是如果可以的话,请将其复制并粘贴到个人文件中。

 function WriteCookie() { customer = document.getElementById('customer'); if (customer.innerHTML == "") { alert("Enter some value!"); return; } cookievalue = escape(customer.innerHTML); document.cookie = "name=" + cookievalue; console.log("name=" + cookievalue); // expires var now = new Date(); now.setMonth(now.getMonth() + 1); document.cookie = "expires=" + now.toUTCString() + ";" // output = document.getElementById('output'); // output.innerHTML = cookievalue; } function ReadCookie() { var allcookies = document.cookie; console.log("All Cookies : " + allcookies); // Get all the cookies pairs in an array cookiearray = allcookies.split(';'); // Now take key value pair out of this array for (var i = 0; i < cookiearray.length; i++) { name = cookiearray[i].split('=')[0]; value = cookiearray[i].split('=')[1]; console.log("Key is : " + name + " and Value is : " + value); } } 
 <html> <head> </head> <body> <form name="myform" action=""> <!-- Enter name: <input type="text" name="customer"/> --> <h4>Enter Name:</h4> <h4 contenteditable="true" id="customer" style="background-color: #eee"></h4> <!-- <h4>Your Name is:</h4> <h4 id="output" style="width: 100%; height: 20px; background-color: #ddd;"></h4> --> <input type="button" value="Set Cookie" onclick="WriteCookie();" /> <input type="button" value="Read Cookie" onclick="ReadCookie();" /> </form> </body> </html> 

Cookies are stored (in the browser) associated with a particular origin. Cookie与特定来源关联(存储在浏览器中)。 Cookies are not supported on pages loaded with file: scheme URLs, as they lack hostnames. 加载file:方案URL的页面不支持Cookie,因为它们缺少主机名。

Use HTTP (or HTTPS) instead. 请改用HTTP(或HTTPS)。

Use localstorage instead. 请改用localstorage it's much easier 这要容易得多

or: also sessionStorage is suitable 或者: 也可以使用sessionStorage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM