Cookie未在所有浏览器中过期/删除

时间:2017-07-12 10:24:30

标签: javascript php cookies

我为我的电子商务网站设置了几个cookie以跟踪用户订购的商品,如果用户选择删除这些商品,也应该删除Cookie,但是由于一些奇怪的原因,safari不会删除这些Cookie。任何其他浏览器正在删除cookie。

以下是该网站的链接,如果有人想看看:(链接不再可用)点击第一项“毯子和毛巾”然后选择3个选项中的任何项目,将其添加到卡然后去购物篮你应该在左上角看到“cookies数量= 5”,如果你订购了更多的物品,它会增加,一旦从购物车中删除所有物品,它应该说“饼干数量= 3”,但在野生动物园中它仍然说5。

的Javascript

 if(confirm("Are you sure you want to delete this item"))
    {
        var i = 1;
        while(true){
            var value = "; " + document.cookie;
            var parts = value.split("; " + "order"+i + "=");
            if(parts.length === 2){
                var results = parts.pop().split(";").shift();
                var temp = results.split(" ");
                if(temp[0] === id)
                {
                    var d = new Date();
                    d.setTime(d.getTime() + 1000*60*60*24*60);
                    var exp = "expires=" + d.toUTCString();
                    var name = "order"+i;
                    temp[2] = temp[2] - 1; **REmove one item from order**
                    var val = temp[0] + " " + temp[1] + " " + temp[2];
                    if(temp[2] === 0){ **if cookie has 0 items then delete cookie**
                        document.cookie = name + "=" + '' + ";" + '=;expires=Thu, 01 Jan 1970 00:00:01 UTC;'+ ";path=/";
                        setNewTotal();
                    }else{
                        document.cookie = name + "=" + val + ";" + exp + ";path=/";
                        setNewTotal();
                    }
                    window.location.reload(true);
                    break;
                }
            }
            i++;
        }

        window.location.reload(false);
    }else{

    }
}
function setNewTotal(){
    var value = "; " + document.cookie;
    var parts = value.split("; " + "totalOrders=");
    if(parts.length === 2) {
        var results =  parts.pop().split(";").shift();
    }
    results = results - 1;
    var d = new Date();
    if(results === 0){
        document.cookie = "totalOrders=" + '' + ";" + '=;expires=Thu, 01 Jan 1970 00:00:01 UTC;' + ";path=/";
    }else{
        d.setTime(d.getTime() + 1000*60*60*24*60);
        var exp = "expires=" + d.toUTCString();
        document.cookie = "totalOrders=" + results + ";" + exp + ";path=/";
    }
}

1 个答案:

答案 0 :(得分:0)

我在删除我指定时间错误的cookie时想出来,似乎所有其他浏览器都忽略了它,除了safari。

旧代码:

  document.cookie = "totalOrders=" + '' + ";" + '=;expires=Thu, 01 Jan 1970 00:00:01 UTC;' + ";path=/";

新代码

 document.cookie = "totalOrders=" + '' + ";" + 'expires=Thu, 01 Jan 1970 00:00:01 UTC;' + ";path=/";

请注意'=; expires = Thu,'已替换为'expires = Thu,'这是因为我已设置 =“totalOrders = “+''+”;“因此不需要 =;

感谢您的帮助,非常感谢:)