乐闻世界logo
搜索文章和话题

How to update and delete a cookie?

1个答案

1

How to Update Cookies:

The basic way to update a cookie is to recreate it with the same name but updated value or attributes. Typically, you use the same method as when setting the cookie. Here's an example using JavaScript:

javascript
// Assume we previously set a cookie named 'user' document.cookie = "user=John; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/"; // Update the cookie's value document.cookie = "user=Mike; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";

In this example, I used document.cookie to set the 'user' cookie. To update it, I used document.cookie again with the new value and the same expiration time and path, which overwrites the old cookie.

How to Delete Cookies:

Deleting a cookie is done by setting its expiration time to a past date. This makes the browser consider the cookie expired and delete it. Here's an example using JavaScript to delete a cookie:

javascript
// Set the cookie document.cookie = "user=John; path=/"; // Delete the cookie document.cookie = "user=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";

In this example, we delete the 'user' cookie by setting the expiration time to January 1, 1970 (a past date). Note that when deleting a cookie, ensure the path matches the one used when setting it, as only cookies with identical names and paths are deleted.

This is the basic method for updating and deleting cookies. In practical applications, these operations are often combined with user login and logout functionalities.

2024年8月12日 11:24 回复

你的答案