Cookie Overview
In the previous section, an immutable framework was used to store the shopping column data, while the product display page was constantly changing, although this could achieve a simulated global variable. Functional, but not rigorous. For example, if you right-click within the navigation frame page and click the [Refresh] command in the shortcut menu, all JavaScript variables will be lost. Therefore, to implement strict cross-page global variables, this method is not feasible. Another mechanism in JavaScript: cookies can meet the requirements of true global variables.
Cookie is a mechanism provided by the browser, which provides the cookie attribute of the document object to JavaScript. It can be controlled by JavaScript and is not a property of JavaScript itself. A cookie is a file stored on the user's hard drive. This file usually corresponds to a domain name. When the browser accesses the domain name again, the cookie is made available. Therefore, cookies can span multiple web pages under one domain name, but cannot be used across multiple domain names.
Different browsers implement cookies differently, but their properties are the same. For example, in Windows 2000 and Windows xp, cookie files are stored in the documents and settingsuserNamecookie folder. The usual naming format is: userName@domain.txt.
The cookie mechanism stores information on the user's hard drive, so it can be used as a global variable. This is one of its biggest advantages. It can be used in the following situations.
(1) Save user login status. For example, the user ID is stored in a cookie so that the user does not need to log in again when he visits the page next time. Many forums and communities now provide this function. Cookies can also set an expiration time. When the time limit expires, the cookie will automatically disappear. Therefore, the system can often prompt users to stay logged in: common options are one month, three months, one year, etc.
(2) Track user behavior. For example, a weather forecast website can display local weather conditions based on the region selected by the user. If you need to select the location every time, it will be cumbersome. When cookies are used, it will become more user-friendly. The system can remember the area visited last time. When the page is opened next time, it will automatically display the last user. Weather conditions in your area. Because everything is done in the background, such a page is as if it is customized for a certain user and is very convenient to use.
(3) Customized page. If the website provides the function of changing the skin or changing the layout, cookies can be used to record the user's options, such as background color, resolution, etc. When the user visits next time, the interface style of the last visit can still be saved.
(4) Create a shopping cart. Just like in the previous example, cookies are used to record the items that the user needs to purchase, and they can be submitted uniformly during checkout. For example, Taobao uses cookies to record the products that users have browsed so that they can be compared at any time.
Of course, the above applications are only some of the applications that cookies can complete, and there are more functions that require global variables. The disadvantages of cookies mainly focus on security and privacy protection. Mainly include the following types:
(1) Cookies may be disabled. When a user pays great attention to personal privacy protection, he is likely to disable the cookie function of the browser;
(2) Cookies are related to the browser. This means that even if you visit the same page, cookies saved by different browsers cannot be accessed from each other;
(3) Cookies may be deleted. Because each cookie is a file on the hard disk, it is likely to be deleted by the user;
(4) Cookie security is not high enough. All cookies are recorded in files in the form of plain text, so if you want to save username, password and other information, it is best to encrypt it in advance.
Set cookies
Each cookie is a name/value pair. You can assign the following string to document.cookie:
document.cookie ="userId=828";
If you want to store multiple name/value pairs at one time, you can use semicolons and spaces (; ) to separate them, for example:
document.cookie="userId=828; userName=hulk";
Semicolons (;), commas (,), equal signs (=) and spaces cannot be used in cookie names or values. It's easy to do this in the name of the cookie, but the value to be saved is undefined. How to store these values? The method is to use the escape() function to encode, which can use hexadecimal representation of some special symbols. For example, spaces will be encoded as "20%", which can be stored in the cookie value, and using this solution can also avoid The emergence of Chinese garbled characters. For example:
document.cookie="str= " escape("I love ajax");
is equivalent to:
document.cookie="str=I love ajax";
When using escape() encoding, you need to use unescape() to decode after taking out the value to get the original cookie value, which has been introduced before.
Although document.cookie looks like a property and can be assigned different values. But it is different from general attributes. Changing its assignment does not mean losing the original value. For example, executing the following two statements continuously:
document.cookie="userId=828";
document.cookie="userName=hulk";
At this time, the browser will maintain two cookies, namely userId and userName, so assigning a value to document.cookie is more like executing a statement like this:
document.addCookie("userId=828");
document.addCookie("userName=hulk");
In fact, the browser sets cookies in this way. If you want to change the value of a cookie, you only need to reassign it, for example:
document.cookie="userId =929";
This sets the cookie value named userId to 929.
Get the value of the cookie
The following describes how to get the value of the cookie. The value of the cookie can be obtained directly from document.cookie:
var strCookie=document.cookie;
This will get a string consisting of multiple name/value pairs separated by semicolons. The / value pair includes all cookies under this domain name. For example:
As can be seen from the output, all cookie values can only be obtained at once, but not Specifying the cookie name to get the specified value is the most troublesome part of dealing with cookie values. Users must analyze this string themselves to obtain the specified cookie value. For example, to obtain the value of userId, you can do this:
This way you get the value of a single cookie.
Using a similar method, you can get the value of one or more cookies. The main technique is still the related operations of strings and arrays.
Set an expiration date for cookies
Up to now, all cookies are single-session cookies, that is, these cookies will be lost after the browser is closed. In fact, these cookies are just Stored in memory without creating corresponding hard disk files.
In actual development, cookies often need to be saved for a long time, such as saving the user's login status. This can be achieved using the following options:
document.cookie="userId=828; expiress=GMT_String";
where GMT_String is a time string expressed in GMT format. This statement is to replace userId This cookie is set to the expiration time represented by GMT_String. After this time, the cookie will disappear and become inaccessible. For example: If you want to set a cookie to expire after 10 days, you can do it like this:
Delete cookie
In order to delete a cookie, you can set its expiration time to a time in the past, for example:
Specify the path where the cookie can be accessed
By default, if a cookie is created on a page, the cookie can also be accessed by other pages in the directory where the page is located. If there are subdirectories under this directory, you can also access it in the subdirectories. For example, a cookie created in www.xxxx.com/html/a.html can be accessed by www.xxxx.com/html/b.html or www.xxx.com/html/some/c.html, but Cannot be accessed by www.xxxx.com/d.html.
In order to control the directories that cookies can access, you need to use the path parameter to set cookies. The syntax is as follows:
document.cookie="name=value; path=cookieDir";
where cookieDir means Directory of accessible cookies. For example:
document.cookie="userId=320; path=/shop";
means that the current cookie can only be used in the shop directory.
If you want to make cookies available throughout the website, you can specify cookie_dir as the root directory, for example:
document.cookie="userId=320; path="/";
Specify the host name that can access the cookie
and the path are similar , the host name refers to different hosts under the same domain, for example: www.google.com and gmail.google.com are two different host names. By default, cookies created in one host cannot be accessed in another host, but they can be controlled through the domain parameter. The syntax format is:
document.cookie="name =value; domain=cookieDomain";
Take Google as an example. To achieve cross-host access, you can write:
document.cookie="name=value;domain=.google.com";
In this way, all hosts under google.com can access the cookie.
Comprehensive example: Constructing a universal cookie processing function
The cookie processing process is relatively complex and has certain similarities. Therefore, several functions can be defined to complete common cookie operations, thereby achieving code reuse. Common cookie operations and their function implementations are listed below.
1. Add a cookie: addCookie(name, value, expiresHours)
This function receives 3 parameters: cookie name, cookie value, and how many hours it will expire. It is agreed here that when expiresHours is 0, no expiration time is set, that is, the cookie disappears automatically when the browser is closed. The function is implemented as follows:
2. Get the cookie value of the specified name: getCookie(name)
This function returns the cookie value named name. If it does not exist, it returns empty. Its implementation is as follows:
3. Delete the cookie with the specified name: deleteCookie(name)
This function can delete the cookie with the specified name. Its implementation is as follows:

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

WebStorm Mac version
Useful JavaScript development tools
