无法使用JavaScript删除Cookie? [英] Cannot delete cookie by using javascript?

查看:87
本文介绍了无法使用JavaScript删除Cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对所有页面使用一个cookie,并且我也希望对所有页面更新此cookie。它将在布局中用作主题值。

I want to use one cookie for all my pages and I want to update this cookie for all pages also. It will be used in layout as a theme value.

我已经使用javascript方法创建了一个名为主题的cookie;

I have created a cookie named as theme by using javascript method;

$.cookie("theme", "skin-blue");

并检查cookie是否通过使用保存;

And checked the cookie whether is saved or not by using;

document.cookie "theme=skin-blue"

当我想通过使用cookie删除cookie时返回false;

When i wanna delete the cookie by using it returns false;

$.removeCookie("theme") false

您能帮我解决这个问题吗?反正有删除或清除或cookie吗?谢谢。

Can you help me to solve the issue? Is there anyway to delete or clear or cookies? Thanks.

注意:此方法适用于一页,但不适用于所有页面。在其他页面中,它会创建相同名称的新cookie,因此我无法更新相关的cookie。

Note: This method works for one page but not for all pages. In other pages it creates new cookie as same name so i cannot update the related one.

推荐答案

删除cookie的标准方法JavaScript中的方法是将cookie的值覆盖为空值,并将date过期为通过日期。

The standard way of deleting a cookie in JavaScript is to overwrite cookie's value to empty value and expires date to a passed date.

示例:
假设您要删除的Cookie称为 access_token 。在下面的行中应删除Cookie,如果Cookie的域在同一个域中,则此方法应该可行。我们假设 access_token cookie在 example.com 域中。

Example: Let's say that cookie you'd like to delete is called access_token. Below line should deleted the cookie, if cookie's domain is in the same domain, then this should work. We assume that access_token cookie is in example.com domain.

// Deleting access_token cookie with implicit domain.
document.cookie = "access_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC;"

但是,如果Cookie的域位于其他域或子域中,域以上行不起作用。让我更精确一些。这次,我们假设 access_token cookie在 .example.com 子域中(请注意example.com前面的点)。然后,以上行不起作用,因此不会删除cookie。

However, If cookie's domain is in a different domain or a sub-domain above line should not work. Let me be more precise. This time, we assume that access_token cookie is in .example.com sub-domain (notice the dot in front of example.com). Then, above line should not work, thus cookie will not be deleted.

解决方案,对于cookie位于另一个域/子域中,那么删除Cookie时必须明确指定域/子域

Solution, for cases where cookie is in a different domain/sub-domain, then you have to explicitly specify domain/sub-domain name while deleting cookie.

// Deleting access_token cookie, with explicit domain/sub-domain
document.cookie = "access_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; domain=.example.com/"

这篇关于无法使用JavaScript删除Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆