


HTML5 Guide-5. Use web storage to store key-value pair data_html5 tutorial tips
The content of this lesson is to introduce web storage, which is used to store key-value pair data in the browser. It functions like the previous cookies, but it is better and can store larger data. There are two types of web storage: local storage and session storage. They use the same implementation mechanism, but have different visibility and life cycles.
1. Use local storage
We use the localStorage object to access local storage. It returns the Storage object. Storage is used to store key-value pair data. It has the following properties and methods:
clear(): Clear the stored key-value pair data;
getItem(
key(
length: Returns the number of key-value pairs;
removeItem(
setItem(
[
Storage object allows us to store key-value pair data in the form of strings. The key is unique, which means that when we use the setItem method to add a key-value pair, if the key value already exists, it will be updated. operation. Let’s look at the following example:
< !DOCTYPE HTML>
There are < span id="count">items
Item Count: | - |
---|
< ;/body>
Let’s take a look at the running results:
The browser cannot delete the data we created through localStorage unless the user deletes it.
2. Listen to Storage events
Data stored through local storage is visible to documents from the same source. For example, if you open two chrome browsers to access the same URL address, on any page The local storage created on the page is also visible to another page. However, if you use another browser (such as Firefox) to open the same URL address, the local storage will not be visible because they have different sources. The Storage event is used to monitor changes in the storage content. Let’s see what attributes it contains:
key: Returns the changed key value;
oldValue: Returns the value before the key value was changed;
newValue: Returns the new value of the changed key value;
url: The changed url address;
storageArea: Returns the changed Storage object (whether it is local storage or session storage).
Let’s look at an example below:
key | oldValue | newValue | url | storageArea |
---|
<script> <br>var tableElement = document.getElementById('data'); <br>window.onstorage = function (e) { <br>var row = '<tr>'; <br>row = '<td>' e.key '< ;/td>'; <br>row = '<td>' e.oleValue '</td>'; <br>row = '<td>' e.newValue '</td>'; <br>row = '<td>' e.url '</td>'; <br>row = '<td>' (e.storageArea == localStorage) '</td></ tr>'; <br>tableElement.innerHTML = row; <br>} <br></script>
The data we added, deleted, and modified storage in Example 1 will be displayed on the Example 2 page. Example 2 runs normally in Chrome browser, but Firefox does not respond. Other browsers have not been tested.
Run result:
3. Use session storage
Session storage is used the same as local storage, except that its accessibility is limited to the current page, and it will disappear after the page is closed. We access it through sessionStorage.
There are items
Item Count: | - |
---|
<script> <br>displayData(); <br>var buttons = document.getElementsByTagName("button"); <br>for (var i = 0; i < buttons.length; i ) { <br>buttons[i].onclick = handleButtonPress; <br>} <br>function handleButtonPress(e) { <br>switch (e.target.id) { <br>case 'add': <br>var key = document.getElementById("key").value; <br>var value = document.getElementById("value").value; <br>sessionStorage.setItem(key, value); <br>break; <br>case 'clear': <br>sessionStorage.clear(); <br>break; <br>} <br>displayData(); <br>} <br>function displayData() { <br>var tableElement = document.getElementById('data'); <br>tableElement.innerHTML = ''; <br>var itemCount = sessionStorage.length; <br>document.getElementById('count').innerHTML = itemCount; <br>for (var i = 0; i < itemCount; i ) { <br>var key = sessionStorage.key(i); <br>var val = sessionStorage.getItem(key); <br>tableElement.innerHTML = "<tr><th>" key ":</th><td>" val "</td></tr>"; <br>} <br>} <br></script>
运行效果:
你在例3中做任何修改,例2的页面不会发生任何改变。
总结:
sessionStorage用于本地存储一个会话(session)中的数据,这些数据只有在同一个会话中的页面才能访问并且当会话结束后数据也随之销毁。因此sessionStorage不是一种持久化的本地存储,仅仅是会话级别的存储。
localStorage用于持久化的本地存储,除非主动删除数据,否则数据是永远不会过期的。
web storage和cookie的区别:Web Storage的概念和cookie相似,区别是它是为了更大容量存储设计的。Cookie的大小是受限的,并且每次你请求一个新的页面的时候Cookie都会被发送过去,这样无形中浪费了带宽,另外cookie还需要指定作用域,不可以跨域调用。除此之外,Web Storage拥有setItem,getItem,removeItem,clear等方法,不像cookie需要前端开发者自己封装setCookie,getCookie。还有,web storage每个域(包括子域)有独立的存储空间,各个存储空间是完全独立的,因此不会造成数据混乱。
但是Cookie也是不可以或缺的:Cookie的作用是与服务器进行交互,作为HTTP规范的一部分而存在 ,而Web Storage仅仅是为了在本地“存储”数据而生。
源码下载

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This website reported on March 7 that Dr. Zhou Yuefeng, President of Huawei's Data Storage Product Line, recently attended the MWC2024 conference and specifically demonstrated the new generation OceanStorArctic magnetoelectric storage solution designed for warm data (WarmData) and cold data (ColdData). Zhou Yuefeng, President of Huawei's data storage product line, released a series of innovative solutions. Image source: Huawei's official press release attached to this site is as follows: The cost of this solution is 20% lower than that of magnetic tape, and its power consumption is 90% lower than that of hard disks. According to foreign technology media blocksandfiles, a Huawei spokesperson also revealed information about the magnetoelectric storage solution: Huawei's magnetoelectronic disk (MED) is a major innovation in magnetic storage media. First generation ME

Vue3+TS+Vite development tips: How to encrypt and store data. With the rapid development of Internet technology, data security and privacy protection are becoming more and more important. In the Vue3+TS+Vite development environment, how to encrypt and store data is a problem that every developer needs to face. This article will introduce some common data encryption and storage techniques to help developers improve application security and user experience. 1. Data Encryption Front-end Data Encryption Front-end encryption is an important part of protecting data security. Commonly used

What is cache? A cache (pronounced ka·shay) is a specialized, high-speed hardware or software component used to store frequently requested data and instructions, which in turn can be used to load websites, applications, services, and other aspects of the system faster part. Caching makes the most frequently accessed data readily available. Cache files are not the same as cache memory. Cache files refer to frequently needed files such as PNGs, icons, logos, shaders, etc., which may be required by multiple programs. These files are stored in your physical drive space and are usually hidden. Cache memory, on the other hand, is a type of memory that is faster than main memory and/or RAM. It greatly reduces data access time since it is closer to the CPU and faster compared to RAM

Git is a fast, reliable, and adaptable distributed version control system. It is designed to support distributed, non-linear workflows, making it ideal for software development teams of all sizes. Each Git working directory is an independent repository with a complete history of all changes and the ability to track versions even without network access or a central server. GitHub is a Git repository hosted on the cloud that provides all the features of distributed revision control. GitHub is a Git repository hosted on the cloud. Unlike Git which is a CLI tool, GitHub has a web-based graphical user interface. It is used for version control, which involves collaborating with other developers and tracking changes to scripts and

How to correctly use sessionStorage to store sensitive information requires specific code examples. Whether in web development or mobile application development, we often need to store and process sensitive information, such as user login credentials, ID numbers, etc. In front-end development, using sessionStorage is a common storage solution. However, since sessionStorage is browser-based storage, some security issues need to be paid attention to to ensure that the stored sensitive information is not maliciously accessed and used.

How do PHP and swoole achieve efficient data caching and storage? Overview: In web application development, data caching and storage are a very important part. PHP and swoole provide an efficient method to cache and store data. This article will introduce how to use PHP and swoole to achieve efficient data caching and storage, and give corresponding code examples. 1. Introduction to swoole: swoole is a high-performance asynchronous network communication engine developed for PHP language. It can

This article is reprinted from the WeChat public account "Living in the Information Age". The author lives in the information age. To reprint this article, please contact the Living in the Information Age public account. For students who are familiar with database operations, writing beautiful SQL statements and finding ways to find the data they need from the database is a routine operation. For students who are familiar with machine learning, it is also a routine operation to obtain data, preprocess the data, build a model, determine the training set and test set, and use the trained model to make a series of predictions about the future. So, can we combine the two technologies? We see that data is stored in the database, and predictions need to be based on past data. If we query future data through the existing data in the database, then it is

Methods and techniques for using PHP arrays to implement data caching and storage. With the development of the Internet and the rapid growth of data volume, data caching and storage have become one of the issues that we must consider during the development process. As a widely used programming language, PHP also provides a wealth of methods and techniques to implement data caching and storage. Among them, using PHP arrays for data caching and storage is a simple and efficient method. 1. Data caching The purpose of data caching is to reduce the number of accesses to the database or other external data sources, thereby improving
