JavaScript 实现Cookie 的写入和读取

cookie是网页通过浏览器保存在用户本地计算机上的数据,用户再次访问该网页的时候,浏览器会将这数据发送给该网页。

Cookie最典型的应是判断注册用户是否已经登陆网站。用户可能会得到提示,是否在一下次进入此网站的时候保留用户信息以便简化登陆手续,也就是“记住密码”,这些所谓的记忆都是用cookie保存的。另一个重要的应用场合是“购物车之类的处理”,用户可能会在一段时间内在同一家的不同页面选择不同的商品,网页把这些信息写入到cookie,以便在付款时候提取信息。

在js中我们用document.cookie这属性来写入cookie和读取cookie

写入cookie的格式:document.cookie='cookiename='+escape('cookievalue')+';expires='+ dataobj.toGMTString()

View Code
 function writeCookie() {
var vdate = new Date();
document.cookie
= "name=" + escape('写入cookie') + ';expires=' + vdate.setTime(vdate.getTime() + 1 * 24 * 60 * 60 * 1000).toGMTString();
}
function readCookie() {
var cookieValue = document.cookie;
var start = cookieValue.indexOf('name=');
if (start != -1) {
start
+= 'name'.length + 1;
var end = cookieValue.indexOf(';', start);
if (end == -1) {
alert(unescape(cookieValue.substring(start)));
}
else {
alert(unescape(cookieValue.substring(start, end)));
}
}
}

  

原文地址:https://www.cnblogs.com/hfliyi/p/2173747.html