- function SetCookie(name, value) {
- var days = 30; //保留30天
- var exp = new Date();
- exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
- var oldCookie = getCookie(name);
- alert("oldCookie is:" + oldCookie);
- if (oldCookie != null) { //如果cookie已有值,检查是否重复和个数
- eval('a=' + value);
- var newCookie = value;
- var count = 0;
- var cookieValueBeginIndex = oldCookie.indexOf("{");
- for (var i = 0; i < oldCookie.length; ) {
- var j = cookieValueBeginIndex;
- for (; oldCookie.charAt(j) != "}"; j++)
- { }
- cookieValueEndIndex = j + 1;
- var subOldCookie = oldCookie.substring(cookieValueBeginIndex, cookieValueEndIndex);
- cookieValueBeginIndex = cookieValueEndIndex;
- eval('b=' + subOldCookie);
- if (a.goodsId != b.goodsId) {
- alert("要添加");
- newCookie += subOldCookie;
- count++;
- if (count == 3) {
- return;
- }
- }
- i = cookieValueEndIndex;
- }
- alert("newCookie is:" + newCookie);
- document.cookie = name + "=" + escape(newCookie) + ";expires=" + exp.toGMTString();
- }
- else { //如果该名字的cookie值为空,创建cookie。
- document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
- }
- }
- function getCookie(name)//取cookie
- {
- var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
- if (arr != null)
- return unescape(arr[2]);
- return null;
- }
- function delCookie(name)//删除cookie
- {
- var exp = new Date();
- exp.setTime(exp.getTime() - 1);
- var cval = getCookie(name);
- if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
- }
- function getgoodsinfo() {
- var ogoods = getCookie("shopId01");
- eval('a=' + ogoods);
- alert(a.img);
- }
- SetCookie("shopId01", "{ goodsId:789,img: 'http://ime.baidu.com'}"); //设置商品cookie
- delCookie("shopId01");
- function getgoodsinfo() {
- var ogoods = getCookie("goodsinfo");
- eval('a=' + ogoods);
- alert(a.img);
- }