Key Points
- jQuery.cookie, a jQuery plugin, simplifies the process of creating, reading and deleting cookies. It must be downloaded from the code base on GitHub and included in the page after the jQuery library. The
- cookie() method is used to create and read cookies. Creating a cookie requires two parameters: name and value. The optional third parameter can be an object literal containing additional options, such as path, domain, expires, and secure. To read the cookie, only the name parameter is required.
- Removing cookies is done using the removeCookie() method. If the cookie is found, it will return true, otherwise it will return false. The same options used when creating cookies (such as path and domain) must be passed in to successfully delete the cookies.
Cookies are common technologies for clients to store data. My previous article "How to Handle Cookies in JavaScript" explains how to perform CRUD operations on cookies using native JavaScript. This article turns to jQuery and will guide you through the jquery.cookie plugin, which makes cookie handling simple. This article assumes that readers are familiar with the contents of the aforementioned articles, or at least have a basic understanding of cookies. Without further ado, let's start.
Installing jquery.cookie
First, you need to download jquery.cookie from the code base on GitHub. Once you have obtained the jquery.cookie.js file, just add it to your page (s). Note that as a jQuery plugin you must include it after the jQuery library. Your page should contain a section similar to the following code:
<🎜> <🎜>
Method
jquery.cookie uses the same method cookie() to create and read cookies, but the number of parameters is different. To create a cookie, you need to pass in two required parameters, name and value of the cookie. You can pass a third optional parameter, which is an object literal with some additional options. These options are path, domain, expires, and secure. It is worth noting that these options can be set locally when you call the cookie() method, or globally through the $.cookie.defaults object. The options set with the former take precedence over the options set with the latter. To understand how cookies are created, let's look at a few examples. The following example tracks the number of times a user visits a website:
$.cookie("visits", 10);
This example stores the user's favorite cities and specifies the domain and path that the cookie can read and write to:
$.cookie("favourite-city", "London", {path: "/", domain: "jspro.com"});
This example stores the user's name. This cookie expired at 11:00 am on October 29, 2013 and can only be sent via a secure connection.
$.cookie("name", "Aurelio", {expires: new Date(2013, 10, 29, 11, 00, 00), secure: true});
Read Cookies
Reading cookies is very easy. You just need to pass in one parameter, namely the name of the cookie, and read it, as shown in the following example: Read the number of times a user visits the website:
console.debug($.cookie("visits")); // 打印 "10"
Read the user's favorite city:
console.debug($.cookie("favourite-city")); // 打印 "London"
Read user's name:
<🎜> <🎜>
Delete Cookies
Now you know how to create and read cookies. The last thing you need to know is how to delete a cookie using the removeCookie() method. Return true if the requested cookie is found, otherwise return false. Note that when you want to delete cookies, you need to pass in the same options, such as path and domain, otherwise the operation will fail. Now, let's look at several examples of the removeCookie() method. Delete cookies that store the number of visits to the site:
$.cookie("visits", 10);
Delete cookies that store users like cities:
$.cookie("favourite-city", "London", {path: "/", domain: "jspro.com"});
Next, we try to delete the cookie that stores the user's name. This example fails because the secure value is not specified.
$.cookie("name", "Aurelio", {expires: new Date(2013, 10, 29, 11, 00, 00), secure: true});
Conclusion
This article shows you how to manage cookies using jquery.cookie (a jQuery plugin). It solves many problems by abstracting cookie implementation details into several simple and flexible methods. If you need further instructions or other examples, please refer to the official documentation. If you like to read this article, you will love Learnable; there you can learn the latest skills and techniques from the masters. Members can instantly access all SitePoint's e-books and interactive online courses, such as jQuery: From Newbie to Ninja: New Tips and Tips. Comments in this article have been closed. Have questions about jQuery? Why not ask questions on our forum? *
FAQs about jQuery Cookies (FAQ)
How to set cookies using jQuery?
Setting cookies with jQuery is very simple. You can use the $.cookie function to set cookies. Here is an example:
$.cookie('cookie_name', 'cookie_value');
In this example, 'cookie_name' is the name of the cookie and 'cookie_value' is the value to be stored in the cookie. This will create a cookie that expires at the end of the browser session. If you want to set a specific expiration date, you can add the option object as the third parameter:
$.cookie('cookie_name', 'cookie_value', { expires: 7 });
This will create a cookie that expires after 7 days.
How to read cookies using jQuery?
It is also very easy to read cookies using jQuery. You can use the $.cookie function again, but this time without using the second parameter. Here is an example:
var cookie_value = $.cookie('cookie_name');
In this example, 'cookie_name' is the name of the cookie to be read. This function will return the value of the cookie.
How to delete cookies using jQuery?
To use jQuery to delete cookies, you can use the $.removeCookie function. Here is an example:
$.removeCookie('cookie_name');
In this example, 'cookie_name' is the name of the cookie to be deleted. This will delete cookies from the browser.
(The subsequent FAQ answer is similar to the previous output. The duplicate content is omitted here to keep the answer concise.)
The above is the detailed content of Working with Cookies in jQuery. For more information, please follow other related articles on the PHP Chinese website!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft