When you browse a website, a very small text file will be generated on your hard disk, which can record information such as your user ID, password, web pages you have browsed, and the time you stayed on it.
When you come to the website again, the website learns your relevant information by reading the cookies, and can take corresponding actions, such as displaying a welcome slogan on the page, or allowing you to enter your ID or password without having to enter it. Just log in and wait. Essentially, it can be thought of as your ID card.
It is very troublesome to use traditional Javascript to set and obtain Cookies information. We need to write several functions to handle it. Fortunately, jQuery does a lot of things for us. With the help of jQuery plug-in, we can easily create, obtain and delete Cookies. . Click here to download the cookie plug-in: http://plugins.jquery.com/project/Cookie
Create Cookie
Setting cookies using jQuery is very easy. For example, we create a cookie named "example" with a value of "foo":
$.cookie("example", "foo");
To set the validity period of the cookie, you can set the expires value, for example, set the cookie expiration time to 10 days:
$.cookie("example", "foo", {expires:10});
Set the cookie to expire in one hour:
var cookietime = new Date();
cookietime.setTime(date.getTime() (60 * 60 * 1000)); //coockie is saved for one hour
$ .cookie("example", "foo",{expires:cookietime});
To set the cookie saving path, you can set the path value, such as setting the path to the root directory:
$.cookie("example", "foo",{path:" /"});
If you want to set the path to /admin, then:
$.cookie("example", "foo",{path:"/admin"});
Get cookie value
Use The method for jQuery to obtain the value of a cookie is quite simple. The following is a pop-up box displaying the value of a cookie named "example":
alert($.cookie("example"));
Delete Cookie
Use jQuery to delete cookies, just add The value of the cookie is null. Note that if the value is set to an empty string, the cookie cannot be deleted, only the cookie value is cleared.
$.cookie("example",null);
After understanding how to set up cookies, in the following article, I will use examples to demonstrate the application of cookies, such as recording the browsing history of website users (browsed products, viewed movie), stay tuned.