[HTML5 Advanced Part 1] Web Storage - cookie, localStorage, sessionStorage

1. Data storage

1.1 cookie

1.1.1 Concept introduction

When we use network functions, one protocol must be indispensable, and that is the HTTP protocol. However, since the HTTP protocol is stateless, it will be disconnected after the connection and no user information will be recorded. At this time, we introduced the concept of cookies.

Native JavaScriptScipt case collection
JavaScript + DOM basic
JavaScript basic to advanced
Canvas game development

Cookies are data stored on the user's local terminal by the website in order to identify the user and track the session. Cookies are carried by default in the HTTP protocol. It has the following features:

  • The stored data can only be in string format;
  • Under the same domain name, the size of the stored files is generally 4KB, and the number is 50;
  • Timeliness, after a certain period of time, the cookie will be destroyed. The shortest validity period is when the browser is closed, the cookie will be destroyed;
  • For security, the same origin policy is adopted, that is, the same protocol, the same domain name, and the same port. Only under these conditions can the data be read.

Next, let’s briefly introduce the operation of cookies:

  • Cookie needs to set name and value;
  • The domain of the cookie is the domain name. Generally, the default setting of the domain is used;
  • Set the cookie path;
  • Set the expires of the cookie, that is, the expiration time of the cookie.

1.1.2 Storage and Acquisition

Cookie format: key = value

View cookies: Open the browser and switch to Application through the exclamation mark in front of the address bar or the console, find Cookies and click on it.

Set and read cookies :

//创建或修改cookie
document.cookie = "name = Jack"; 

//创建变量接收读取到的cookie值,并打印
var getCookie = document.cookie;  
console.log(getCookie); 

//通过添加expires设置过期时间	
document.cookie = "name=;expires=Thu, 01 Jan 1970 00:00:00 GMT";

Note: 1. The expiration time of the cookie setting is based on the server time. After the browser obtains any HTTP response header from the server, the browser's time will be synchronized with the server.

  2. 使用new Date() 获取的本地时间并不准确,与服务器相差很大。本地时间可被客户修改,如果cookie使用本地时间可被人利用实现永久免登陆验4

Use of cookies :

添加cookie:document.cookie = “key=value”; // 一次写入一个键值对
document.cookie = 'test1=hello';
document.cookie = 'test2=world';
//在浏览器中查看一下现在的cookie是什么样子   打开控制台 点击application 就能看到cookies
//注意 document.cookie一次只能写入一个 Cookie,而且写入并不是覆盖,而是添加

读取cookie:document.cookie;

document.cookie // "test1=hello; test2=world"
上面代码从document.cookie一次性读出两个 Cookie,它们之间使用 分号空格 分隔。必须手动还原,才能取出每一个 Cookie 的值。

var cookies = document.cookie.split('; ');

for (var i = 0; i < cookies.length; i++) { 
      console.log(cookies[i]);
}
// foo=bar// baz=bar

修改cookie:document.cookie = “key=value”;  // 修改名为key的cookie值

document.cookie = 'test2=hah';
document.cookie // "test1=hello; test2=hah"

上面代码修改了test2对应的值

失效时间:expires ,没有设置失效时间的cookie 在浏览器关闭以后就会自动删除,如果设置了失效时候在未来的时间,就可以让cookie保存的时间长一点
设置失效时间:document.cookie = “key=value;expires=”+ oDate;

var oDate = new Date();
oDate.setDate(oDate.getDate() + 7);
document.cookie = “key=value;expires=”+ oDate;
//上面代码设置cookie的过期时间为7天以后

删除cookie:将cookie值覆盖为空,并将失效时间设置为过去的时间。

var oDate = new Date();
oDate.setDate(oDate.getDate() -7);
document.cookie = “test=;expires=”+ oDate;
//将cookie的过期时间设置为 7天前,test 这个cookie 就获取不到

1.1.3 Encapsulation of methods

function setCookie(name,value,n){
	var oDate = new Date();
	oDate.setDate(oDate.getDate()+n);
	document.cookie = name+"="+value+";expires="+oDate;
}

function getCookie(name){
	var str = document.cookie;
	var arr = str.split("; ");
	for(var i = 0; i < arr.length; i++){
		//console.log(arr[i]);
		var newArr = arr[i].split("=");
		if(newArr[0]==name){
			return newArr[1];
		}
	}
}

function removeCookie(name){
	setCookie(name,1,-1);
}

1.1.4 Summary

As can be seen from the above, cookies are not suitable for storing large amounts of data because they are passed by each server request, making cookies very slow and inefficient;

In HTML5, two new ways of storing data on the client side are provided:

  • localStorage data storage without time limit
  • sessionStorage is a data storage for a session

Both data are not passed by every server request, but the data is only used when requested, which makes it possible to store large amounts of data without affecting the performance of the website.

For different websites, data is stored in different areas, and a website can only access its own data.

1.2 localstorage 与 sessionstorage

1.2.1 Overview

localStorage Permanent level storage. As long as you visit any page in this domain name again, you can extract the data. The data will remain there as long as the browser is not uninstalled. Of course, we can delete data manually.

sessionStorage session-level storage. It is only valid in the current page, the data will be destroyed when the page is closed, and the pages cannot access each other.

Location in browser:

Insert image description here

Note: 1. localStorage and sessionStorage are exactly the same in use, that is, they have the same API. The difference is what was mentioned above

2. Local storage data format JSON string (key-value format)

1.2.2 Properties or methods for operating data

H5 encapsulates the attributes and methods of localstorage as follows:

  • localstorage.length Get the number of key-value pairs currently stored
  • localstorage.key(n) gets the key value of the nth item
  • localstorage.setItem(key,value) sets the corresponding key-value pair
  • localstorage.getItem(key) Gets the data corresponding to the key value
  • localstorage.removeItem(key) clears certain data
  • localstorage.clear() clears all stored data

In addition to setting and obtaining localStorage through the above H5 encapsulated methods, you can also use the dot (.) operator or [] to set and obtain data like a normal object :

// 以animal名字将json串catStr存储到localStorage中   	  
localStorage.animal = catStr;
localStorage["animal"] = catStr;

Insert image description here

1.2.3 Case - Submit Questionnaire

Insert image description here

Code example :

<h1>新型肺炎防治知识试题</h1>
<form>
    <div>
        <h3>Q1:为控制“新型冠状病毒感染的肺炎”疫情的传播、蔓延、医务人员应做到( )</h3>
        <div><input type="radio" name="q1">早发现、早报告、早诊断、早治疗</div>
        <div><input type="radio" name="q1">早发现、早报告、早诊断、早转院、早治疗</div>
        <div><input type="radio" name="q1">早发现、早诊断、早隔离、早治疗</div>
        <div><input type="radio" name="q1">早发现、早报告、早诊断、早治疗</div>
    </div>
    <div>
        <h3>Q2:为控制“新型冠状病毒感染的肺炎”疫情的传播、蔓延、医务人员应做到( )</h3>
        <div><input type="radio" name="q2">早发现、早报告、早诊断、早治疗</div>
        <div><input type="radio" name="q2">早发现、早报告、早诊断、早转院、早治疗</div>
        <div><input type="radio" name="q2">早发现、早诊断、早隔离、早治疗</div>
        <div><input type="radio" name="q2">早发现、早报告、早诊断、早治疗</div>
    </div>
    <div>
        <h3>Q3:为控制“新型冠状病毒感染的肺炎”疫情的传播、蔓延、医务人员应做到( )</h3>
        <div><input type="radio" name="q3">早发现、早报告、早诊断、早治疗</div>
        <div><input type="radio" name="q3">早发现、早报告、早诊断、早转院、早治疗</div>
        <div><input type="radio" name="q3">早发现、早诊断、早隔离、早治疗</div>
        <div><input type="radio" name="q3">早发现、早报告、早诊断、早治疗</div>
    </div>
    <div>
        <h3>Q4:为控制“新型冠状病毒感染的肺炎”疫情的传播、蔓延、医务人员应做到( )</h3>
        <div><input type="radio" name="q4">早发现、早报告、早诊断、早治疗</div>
        <div><input type="radio" name="q4">早发现、早报告、早诊断、早转院、早治疗</div>
        <div><input type="radio" name="q4">早发现、早诊断、早隔离、早治疗</div>
        <div><input type="radio" name="q4">早发现、早报告、早诊断、早治疗</div>
    </div>
    <div>
        <h3>Q5:为控制“新型冠状病毒感染的肺炎”疫情的传播、蔓延、医务人员应做到( )</h3>
        <div><input type="radio" name="q5">早发现、早报告、早诊断、早治疗</div>
        <div><input type="radio" name="q5">早发现、早报告、早诊断、早转院、早治疗</div>
        <div><input type="radio" name="q5">早发现、早诊断、早隔离、早治疗</div>
        <div><input type="radio" name="q5">早发现、早报告、早诊断、早治疗</div>
    </div>
    <input type="submit" value="提交">
</form>
<script>
    var form = document.querySelector("form");

    form.onsubmit = function(){
        if(localStorage.submit){
            alert("不能重复提交");
        }else{
            localStorage.submit = true;
            alert("表单成功提交...")
        }
    }
</script>

1.2.4 Benefits brought by Web Storage

  • Reduce network traffic: Once the data is saved locally, it can avoid requesting data from the server, thus reducing unnecessary data requests and reducing unnecessary data transfer back and forth between the browser and the server.

  • Quickly display data: The performance is good, reading data locally is much faster than obtaining data from the server through the network, and local data can be obtained instantly. In addition, the web page itself can also be cached, so if the entire page and data are local, it can be displayed immediately.

  • Temporary storage: Many times the data only needs to be used while the user is browsing a set of pages, and the data can be discarded after closing the window. In this case, sessionStorage is very convenient.

appendix:

1. Data persistence technology (offline storage) provided by HTML5

  • Application Cache: The files required by the local cache application (save the application itself does not save data)
  • LocalStorage and SessionStorage store data in key-value pair (JSON string) format
  • Web SQL relational database, accessed through SQL statements
  • IndexDB index database

2. Application Cache

  • Case link: http:// m.ftchinese.com/phone.html
  • Application technology: Application Cache, LocalStorage, Web SQL
  • Application Cache key: Manifest file (list of files required by the application)
  • Application cache features: the Manifest file is updated only when there is a change, and all files in the Manifest must be updated once to take effect next time (the update is not timely)

Guess you like

Origin blog.csdn.net/qq_39335404/article/details/132663795