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

Example analysis of cookie object usage in javascript_javascript skills

WBOY
Release: 2016-05-16 16:16:49
Original
1061 people have browsed it

The examples in this article describe the usage of cookie objects in JavaScript. Share it with everyone for your reference. The details are as follows:

Attributes

name The only attribute that must be set, indicating the name of the cookie
expires Specifies the lifetime of the cookie. If it is not set, it will automatically expire when the browser is closed
path determines the availability of the cookie to the server for other web pages. Generally, the cookie is available to all pages in the same directory. When the path attribute is set, the cookie is only valid for all web pages under the specified path and sub-path
domain Many servers are composed of multiple servers. The domain attribute mainly sets multiple servers in the same domain to share a cookie. If web server a needs to share cookies with web server b, the domain attribute of a's cookie needs to be set to b, so that a The created cookie can be shared by a and b
secure Generally, websites that support SSL start with HTTPS. The secure attribute can set cookies that can only be accessed through HTTPS or other security protocols

Cookies are essentially strings

Generally speaking, cookies cannot contain special characters such as semicolons, commas, and spaces. However, these characters can be transmitted using encoding, that is, the special characters in the text string are converted into corresponding hexadecimal ASCII values. Use the encodeURI() function to convert text characters into a valid URI, and use the decodeURI() function to decode

Write cookie

var cookieTest ="name=userName"; 
document.cookie= cookieTest; //存入 
//用分号分割不同属性 
var date = newDate(); 
date.setDate(date.getDate()+7); //设置cookie的存活时间为一星期 
document.cookie= encodeURI("name=user")+";expires="+date.toUTCString(); 

Copy after login

Read cookie

var cookieString= decodeURI(document.cookie); 
var cookieArray= cookieString.split(";"); 
for(vari=0;i< cookieArray.length;i++){ 
  var cookieNum = cookieArray[i].split("="); 
  var cookieName = cookieNum[0]; 
  var cookieValue = cookieNum[1]; 
} 

Copy after login

Delete cookies

var date = newDate(); 
date.setTime(date.getTime()-10000); 
document.cookie= "name=User;expires="+date.toGMTString; 
//删除一个cookie就是将其过期时间设置为过去的一个时间值 

Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

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