如何在页面之间的cookie中维护选定的项目?每页都覆盖前一页的内容

How to maintain selected items in a cookie between pages? Each page is overwriting the contents from the previous page

本文关键字:覆盖 一页 项目 之间 cookie 维护      更新时间:2023-09-26

我有很多页面,每个页面上都有复选框。当用户单击页面上的复选框时,它将一个值(共享类ID)写入basket。然后将basket写入cookie,以便在页面&amp之间检索;页面刷新。

用户应该只被允许写最多5个共享类到cookie。如果用户试图添加更多,他们会收到警告,并且复选框未选中。

这一切都是由一个脚本,拦截点击,这是加载到每个页面。

问题是我得到的结果不一致。如果我同时加载pageA和pageB,然后单击pageA中的复选框,那么共享类将被添加到篮子中并写入cookie。如果然后单击pageB中的复选框,则cookie将被第二个页面的共享类覆盖。点击pageA上的另一个共享类会用我在pageA中点击的2个共享类覆盖cookie,如果我然后点击pageB中的另一个共享类,cookie(现在包含来自pageA的2个共享类)会被来自pageB的2个共享类覆盖。

看起来每个加载的页面都存在一个basket对象,并且每个页面的内容决定了cookie的内容。我怎样才能使所有页面之间只有一个全局basket对象?

以下代码在每次页面加载时运行:

var basket = {};
jq15(document).ready(function ($) {
    initialiseCookieKeepAlive();
    $('.fund-compare-check-box').live('click', function () {
        if (basket[$(this).val()]) { 
            // if the basket already contains a Share Class, remove it
            RemoveShareclassFromBasket($, $(this).val());
        } else {
            var cookie = getCookie("fund_basket"); // get the cookie
            if (cookie) { // the cookie isn't empty
                if (cookie.split(".").length < 5) { 
                    // if the basket isn't full, add the share class
                    basket[$(this).val()] = $(this).val();
                } else {
                    alert("You have selected the maximum number of share classes");
                    return false;
                }
            } else { // the cookie is empty, so just add the share class
                basket[$(this).val()] = $(this).val();
            }
        }
        // when I've added or removed the share class, 
        // I want to replace the cookie with
        // the latest contents of the basket.
        WriteBasketToCookie();
    });
});
function initialiseCookieKeepAlive() {
    // this function is because they want the basket to last as long
    // as they have any of the relevant pages open, but not
    // the other pages in the site. That's why I didn't create a 'session' cookie
    keepCookieAlive("fund_basket");
    setInterval(function () {
        keepCookieAlive("fund_basket");
    }, 5 * 1000);
}
function keepCookieAlive(cookie) {
    if (getCookie(cookie)) {
        document.cookie = cookie + "=" + getCookie(cookie) + ";expires=" + getTime() + ";path=/";
    }
}

function RemoveShareclassFromBasket($, shareClassId) {
    delete basket[shareClassId];
    WriteBasketToCookie();
}
function WriteBasketToCookie() {
    var arr = new Array();
    for (shareClass in basket) {
        if (!isNaN(shareClass)) {
            arr.push(basket[shareClass]);
        }
    }
    document.cookie = "fund_basket=" + arr.join('.') + ";expires=" + getTime() + ";path=/";
}
function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^'s+|'s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}
function ReCheckBoxes($) {
    if (getCookie("fund_basket")) {
        var cookie = getCookie("fund_basket").split(".");
        $('.fund-compare-check-box').attr('checked', false);
        for (var idx in cookie) {
            basket[cookie[idx]] = cookie[idx];
        }
        $('.fund-compare-check-box').each(function () {
            for (var idx in cookie) {
                if (cookie[idx] == $(this).val()) {
                    $(this).attr('checked', true);
                }
            }
        });
    } else { $('.fund-compare-check-box').attr('checked', false); }
}
function getTime() {
    var today = new Date();
    today.setTime(today.getTime());
    var expires = 20 * 1000;
    var exdate = new Date(today.getTime() + (expires));
    return exdate.toUTCString();
}

这周也遇到了同样的问题。我必须在cookie中存储一个数据数组。我是这样做的。请注意,我正在使用jquery $。Cookie插件(https://github.com/carhartl/jquery-cookie)

var ArrayCookie = function () {
    var cookieName = 'your_cookie_name_here';
    var cookie = $.cookie(cookieName, { path: '/' });
    var store = (cookie) ? JSON.parse(cookie) : [];
    return {
        add: function (title, text) {
            var new_Item = {
                title: title,
                text: text
            };
             store.push(new_Item);
             this.save();
        },
        remove: function (index) {
            store.splice(index, 1);
            this.save();
        },
        count: function () {
            if (this.list() == null || this.list().length < 1)
                return 0;
            return this.list().length;
        },
        list: function () {
            return store;
        },
        save: function () {
            $.cookie(cookieName, JSON.stringify(store), { path: '/' });
        }
    };
};

例子:

var cookie = new ArrayCookie();
cookie.list();                                  // returns the array
cookie.remove(1);                       // remove's item on index 1
cookie.add('title', 'some text');       // add's new item
对于IE,你还需要包含这个javascript文件来支持jsonhttps://github.com/douglascrockford/JSON-js/blob/master/json2.js