Home Web Front-end JS Tutorial Detailed example of reading and writing cookies in js_javascript skills

Detailed example of reading and writing cookies in js_javascript skills

May 16, 2016 pm 04:52 PM

A cookie is a small piece of information, a string of key/value pairs stored on the computer's hard drive. The storage capacity of a cookie is about 4kb. Different browser manufacturers have slightly different restrictions on cookie size; the main features of cookies The essence is "identification" and doing something through identification; cookies cannot obtain any other data from your hard drive, transmit computer viruses or obtain your email address. Cookies have a validity period. The default validity period of a cookie is from when the cookie is generated to when the browser is closed. You can also specify the expiration date by setting the validity period of the cookie. Users can also disable cookies or manually delete cookies.

Cookie is a string and a text string in a specific format

Format: cookieName=cookieValue;expires=expiresDate;path=URLpath;domain=siteDomain//cookie name, expiration date, Store the URL and store the domain value;

How to create cookies

We generally encapsulate cookie settings into a function:

Copy code The code is as follows:

function addCookie(sName,sValue,day) {
var expireDate = new Date();
expireDate.setDate(expireDate.getDate() day);;
//Set expiration time
document.cookie = escape(sName) '=' escape(sValue) ';expires=' expireDate.toGMTString() ;6 //escape() convert Chinese characters into unicode encoding, toGMTString() convert date object into string
}

Read cookie

After adding the cookie, how do we get it? It’s very simple:
Copy code The code is as follows:

function getCookies() {
var showAllCookie = '';
if(!document.cookie == ''){
var arrCookie = document.cookie.split('; ');
//Use split('; ') to cut all cookies and save them in the array arrCookie
var arrLength = arrCookie.length;
for(var i=0; i<arrLength; i ) {
showAllCookie = 'c_name:' unescape(arrCookie[i].split('=')[0]) 'c_value:' unescape(arrCookie[i].split('=')[1]) '<br>' 9 }
return showAllCookie;
}
}

Cookies have a validity period and can be automatically deleted, or they can be deleted immediately by setting their expiration date.

Same as Simple, continue:
Copy code The code is as follows:

function removeCookie() {
if(document.cookie != '' && confirm('Do you want to clear all cookies? ')) {
var arrCookie = document.cookie.split('; ');
var arrLength = arrCookie.length;
var expireDate = new Date();
expireDate.setDate(expireDate .getDate()-1);
for(var i=0; i<arrLength; i ) {
var str = arrCookie[i].split('=')[0];
document .cookie = str '=' ';expires=' expireDate.toGMTString();
}
}
}

We already know how to create, obtain, and delete cookies , now it’s time to use cookies

Let’s use cookies to make a simple timer:
Copy code The code is as follows:

var cookieCount = {};
cookieCount.count = function () {
var count = parseInt(this.getCount('myCount'));
count ;
document.cookie = 'myCount=' count '';
alert('count 'visits');
}
cookieCount.setCount= function () {
/ /First create a cookie named myCount
var expireDate = new Date();
expireDate.setDate(expireDate.getDate() 1);
document.cookie = 'myCount=' '0' ';expires=' expireDate.toGMTString();
}
cookieCount.getCount = function (countName) {
//Get the cookie named count and add 1 to it
var arrCookie = document. cookie.split('; ');
var arrLength = arrCookie.length;
var ini = true;
for(var i=0; i<arrLength; i ) {
if(countName == arrCookie[i].split('=')[0]){
return parseInt(arrCookie[i].split('=')[1]);
break;
}else {
ini = false;
}
}
if(ini == false)this.setCount();
return 0;
}
cookieCount.count() ;

Cookie path

The cookie path was mentioned at the beginning of this article. Set the cookie path: path=URL;

If it is created in a subdirectory of the domain name Cookies, domain names and other sibling or superior directories cannot access this cookie. The advantage of setting the path is that it can access the domain name and subcategory directories of the domain name, as follows:

document. cookie='cookieName=cookieValue;expires=expireDate;path=/'.

cookie domain

Set domain: domain=siteDomain

This is mainly used to share a cookie in the same domain, such as "www.taobao .com" and "ued.taobao.com" share the same domain name "taobao.com". If we want the cookies under "www.taobao.com" to be accessed by "ued.taobao.com", then we need to Set the path attribute to "/", and set the domain of the cookie-->document.cookie='cookieName=cookieValue;expires=expireDate;path=/;domain=taobao.com'.

With the continuous development of web projects, HTML5 provides two properties, window.sessionStorage and window.localStorage, and carries methods such as setItem, getItem, removeItem, clear, etc., making it possible to store data locally. Operation is simpler and more convenient
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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Replace String Characters in JavaScript

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

Custom Google Search API Setup Tutorial

Example Colors JSON File Example Colors JSON File Mar 03, 2025 am 12:35 AM

Example Colors JSON File

8 Stunning jQuery Page Layout Plugins 8 Stunning jQuery Page Layout Plugins Mar 06, 2025 am 12:48 AM

8 Stunning jQuery Page Layout Plugins

10 jQuery Syntax Highlighters 10 jQuery Syntax Highlighters Mar 02, 2025 am 12:32 AM

10 jQuery Syntax Highlighters

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

Build Your Own AJAX Web Applications

What is 'this' in JavaScript? What is 'this' in JavaScript? Mar 04, 2025 am 01:15 AM

What is 'this' in JavaScript?

10  JavaScript & jQuery MVC Tutorials 10 JavaScript & jQuery MVC Tutorials Mar 02, 2025 am 01:16 AM

10 JavaScript & jQuery MVC Tutorials

See all articles