Home > Web Front-end > JS Tutorial > body text

How to set cookies in javascript

青灯夜游
Release: 2023-01-05 16:09:41
Original
20168 people have browsed it

In JavaScript, you can use the cookie attribute of the document object to set, read or delete cookies, the syntax is "document.cookie="cookieName=Value;expires=expiration time";".

How to set cookies in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

1. What is a cookie?

The HTTP used to load web pages into the browser is a "stateless" protocol, also That is to say, when the server sends the page to the browser, it considers the thing to be completed and does not save any information. This makes it difficult to maintain some kind of continuity during a browser session, such as recording what content a user has accessed or downloaded, or recording the user's login status in a private area.

Cookie is a way to solve this problem. For example, a cookie can record the user's last visit, save a list of the user's preferences, or save the items in the shopping cart as the user continues shopping. When used correctly, cookies can improve the user experience of the site.

The cookie itself is a short string of information that can be saved on the user's computer by the page and can then be read by other pages. Cookies are generally set to expire after a certain period of time.

Limitations of cookies

Browsers have limitations on the number of cookies that can be saved, usually a few hundred or more. Generally, 20 cookies per domain are allowed, and each domain can store up to 4KB of cookies.

In addition to the problems that may be caused by size restrictions, there are many reasons that may cause cookies on the hard disk to disappear, such as reaching the expiration date, or the user clearing the cookie information, or switching to another browser. . Therefore, cookies should never be used to save important data, and when writing code, you must consider the situation when the expected cookies cannot be obtained

2, document.cookie Properties

JavaScript uses the cookie property of the document object to create, read, and delete cookies.

Each cookie is basically a string consisting of a paired name and value, like this:

username=sam
Copy after login

When the page is loaded into the browser, The browser will collect all cookies related to the page and put them in the document.cookie attribute similar to a string. In this attribute, each cookie is separated by a semicolon:

username=sam;location=China;
Copy after login

#I call document.cookie a "string-like" attribute because it is not a real string, it is just extracting When cookie information is used, this attribute behaves like a string.

Encoding and decoding of data

Certain characters cannot be used in cookies, including points. symbols, commas, and whitespace characters (such as spaces and tabs). Before storing data in a cookie, the data needs to be encoded so that it can be stored correctly.

Before storing information, use JavaScript's escape() function to encode, and when obtaining the original cookie data, use the corresponding unescape() function to decode.

The excape() function converts any non-ASCII characters in the string to the corresponding 2-digit or 4-digit hexadecimal format, such as spaces are converted to , & is converted to &.

For example, the following code will output the original string saved in the variable str and the result after escape() encoding:

<html>
<head>
<script>
function hello(){
	var str = &#39;Here is a (short) piece of text.&#39;;
	document.write(str = &#39;<br />&#39; + escape(str));
	}
</script>
</head>
<body>
<div id="div1">hello owrld</br>
<input type="button" name="111" οnclick="hello()" value = "来按我呀">
</div>
</body>
</html>
Copy after login

You can see To the space is represented as, the left bracket is (, the right bracket is).

3, cookie composition

The information in document.cookie looks like it consists of pairs of names and values String, the form of each pair of data is:

name=value
Copy after login

But in fact, each cookie also contains some other related information, which are introduced separately below.

cookieName and cookieValue

cookieName and cookieValue are the names and values ​​in name=value seen in the cookie string.

domain

The domain attribute indicates to the browser which domain the cookie belongs to. This attribute is optional. When not specified, the default value is the domain of the page where the cookie is set.

The function of this attribute is to control the operation of cookies by subdomains. In terms of distance, if it is set to www.example.com, then the page in the subdomain code.example.com cannot read this cookie. But if the domain attribute is set to example.com, then the page in code.example.com can access this cookie.

path

The path attribute specifies the directory where cookies can be used. If you only want pages in the directory documents to set the cookie value, set the path to /documents. This attribute is optional, and the commonly used default path is /, indicating that the cookie can be used throughout the domain.

secure

secure属性是可选的,而且几乎很少使用。它表示浏览器在把整个cookie发送给服务器时,是否应该使用SLL安全标准。

expires

每个cookie都有一个失效日期,过期就自动删除了。expires属性要以UTC时间表示。如果没有设置这个属性,cookie的生命期就和当前浏览器会话一样长,会在浏览器关闭时自动删除。

4,编写cookie

要编写新的cookie,只要把包含所需属性的值赋予document.cookie就可以了:

document.cookie = "username=sam;expires=15/05/2018 00:00:00"
Copy after login

使用javascript的Date对象可以避免手工输入日期和时间格式;

var cookieDate = new Date(2018,05,15);
document.cookie = "username=sam;expires="+cookieDate.toUTCString();
Copy after login

这样就能达到和前面一样的结果。

#注意这里使用了cookieDate.toUTCString()函数,而不是cookieDate.toString();这是因为cookie的时间要以UTC格式设置。

在实际编码时,应该用excape()函数来确保在给cookie赋值时不会有非法字符:

var cookieDate = new Date(2018,05,15);
var user = "Sam Jones";
document.cookie = "username="+excape(user)+";expires="+cookieDate.toUTCString();
Copy after login

5,编写cookie的函数

很自然就会想到编写一个函数专门用于生成cookie,完成编码和可选属性的组合操作。下面的程序清单就列出了一个这样的程序代码:

function createCookie(name,value,days,path,domain,secure){
	if(days){
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = date.toGMTString();
		}
		else var expires = "";
		cookieString = name + "=" +excape(value);
		if(expires) cookieString += ";expires=" +expires;
		if(path) cookieString += ";path=" + escape(path);
		if(domain) cookieString += ";domain=" + escape(domain);
		if(secure) cookieString += ";secure=" + escape(secure);
		document.cookie = sookieString;
		}
Copy after login

    这个函数的执行的操作是相当直观的,name和value参数组合得到"name = value",其中的value还经过编码以避免非法字符。

    在处理有效期时,使用的参数不是具体日期,而是cookie有效的天数。函数根据这个天数生成有效的日期字符串。

    其他属性都是可选的,如果设置了,就会附加到组成cookie的字符串里。

【推荐学习:javascript高级教程

The above is the detailed content of How to set cookies in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template