获取 cookie,添加新值并使用 jquery 和 json 值再次设置它
我尝试列出一份最喜欢的产品清单。每个产品都有自己的 ID,它是 var ProductID,并且可以在任何页面上访问。我想要达到的目标是在 cookie 中包含一个 json 值。添加新产品后,获取cookie值,添加新的productID,并使用添加的值再次设置cookie
{"0": "11","1": "17","2":"7"}
$.fn.memoProducts = function(options){
options= $.extend({
cookie_name: "memoProducts",
cookie_path: "/",
cookie_expires: 3,
}, options);
function setCookie() {
var cookieValues = getCookie();
var cookie_value_add = [];
cookie_value_add = cookieValues ? $.parseJSON(cookieValues): [];
cookie_value_add.push(productID);
cookie_value = JSON.stringify(cookie_value_add);
var date = new Date;
date.setTime(date.getTime()+(options.cookie_expires*24*60*60*1000));
document.cookie = options.cookie_name+"="+cookie_value+"path="+options.cookie_path+";expires="+date.toGMTString();
}
function getCookie() {
if (document.cookie) {
var values = document.cookie.split(options.cookie_name+"=")[1];
if (values) {
return values.split(";")[0];
}
}
return false;
}
$(this).click(function(e){
setCookie();
});
}
$(function() {
$("a.bookmark").memoProducts();
})
我不知道如何让它发挥作用。第一个错误是:cookie_value_add 为空。仅使用此设置 cookie:
cookie_value = productID;
工作正常,但总是覆盖之前设置的值。也许有人有一个想法......
i try to make a list of favorit products. every product has its own id, it's the var productID and it's already accessible on any page. what i want to reach, is having a json-value in the cookie. after adding a new product, get the cookies value, add the new productID, an set the cookie again with the added value
{"0": "11","1": "17","2":"7"}
$.fn.memoProducts = function(options){
options= $.extend({
cookie_name: "memoProducts",
cookie_path: "/",
cookie_expires: 3,
}, options);
function setCookie() {
var cookieValues = getCookie();
var cookie_value_add = [];
cookie_value_add = cookieValues ? $.parseJSON(cookieValues): [];
cookie_value_add.push(productID);
cookie_value = JSON.stringify(cookie_value_add);
var date = new Date;
date.setTime(date.getTime()+(options.cookie_expires*24*60*60*1000));
document.cookie = options.cookie_name+"="+cookie_value+"path="+options.cookie_path+";expires="+date.toGMTString();
}
function getCookie() {
if (document.cookie) {
var values = document.cookie.split(options.cookie_name+"=")[1];
if (values) {
return values.split(";")[0];
}
}
return false;
}
$(this).click(function(e){
setCookie();
});
}
$(function() {
$("a.bookmark").memoProducts();
})
i don't know how to get it working. first error is: cookie_value_add is null. setting a cookie with only this:
cookie_value = productID;
works fine, but always overwrites the values set before. maybe somebody has got an idea...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论