When you browse a website, a very small text file will be generated on your hard disk, which can record your user ID, password, browsed webpage, stay time, and other information.
When you come to this website again, the website can read Cookies and learn your related information to make corresponding actions, such as displaying your welcome slogans on the page, or you can log on directly without entering the ID or password. Essentially, it can be viewed as your ID card.
It is very troublesome to use traditional Javascript to set and obtain Cookies. You need to write a few functions for processing. Fortunately, jQuery has done a lot for us. With the help of the jQuery plug-in, we can easily create, retrieve, and delete Cookies. Click here to download cookies plug-in: http://plugins.jquery.com/project/Cookie
Create Cookie
Setting cookies with jQuery is very simple. For example, we create a cookie named "example" with the value of "foo:
Copy codeThe Code is as follows:
$. Cookie ("example", "foo ");
To set the cookie validity period, you can set the expires value. For example, set the cookie expiration time to 10 days:
Copy codeThe Code is as follows:
$. Cookie ("example", "foo", {expires: 10 });
Set the cookie to expire in one hour:
Copy codeThe Code is as follows:
Var cookietime = new Date ();
Cookietime. setTime (date. getTime () + (60*60*1000); // coockie saves for one hour
$. Cookie ("example", "foo", {expires: cookietime });
To set the cookie storage path, you can set the path value. For example, set the path to the root directory:
Copy codeThe Code is as follows:
$. Cookie ("example", "foo", {path :"/"});
If you want to set the path to/admin, then:
Copy codeThe Code is as follows:
$. Cookie ("example", "foo", {path: "/admin "});
Get cookie value
Using jQuery to obtain the cookie value is quite simple. The following is a pop-up box showing the cookie value named "example:
Copy codeThe Code is as follows:
Alert ($. cookie ("example "));
Delete Cookie
To delete a cookie using jQuery, you only need to set the cookie value to null. Note that if a string with a null value is set, the cookie cannot be deleted, but the cookie value is cleared.
Copy codeThe Code is as follows:
$. Cookie ("example", null );
After learning about how to set cookies, I will use an instance to demonstrate how to use cookies, if you want to record the history of website users (browsed products and movies), stay tuned.