Home Web Front-end H5 Tutorial How to use HTML5-Web storage?

How to use HTML5-Web storage?

Jun 20, 2017 am 10:30 AM
h5 web storage

Web storage, a better local storage method than cookies

localStorage and sessionStorage

 localStorage-data storage without time limit

 sessionStorage-data storage for a session

1

2

//是否支持if(typeof(Storage)!=="undefined")

{// 是的! 支持 localStorage  sessionStorage 对象!// 一些代码.....} else {// 抱歉! 不支持 web 存储。}

Copy after login

localStorage object

There is no time limit for the data stored in the localStorage object

1

2

localStorage.sitename="小南瓜";

document.getElementById("result").innerHTML="网站名:" + localStorage.sitename;

Copy after login

Whether it is localStorage or sessionStorage, the APIs that can be used are the same, and the commonly used ones are as follows (localStorage For example):

1

2

3

4

5

保存数据:localStorage.setItem(key,value);

读取数据:localStorage.getItem(key);

删除单个数据:localStorage.removeItem(key);

删除所有数据:localStorage.clear();

得到某个索引的key:localStorage.key(index);

Copy after login

Tips: Key/value pairs are usually stored as strings, and you can convert this format according to your needs.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

if(typeof(Storage)!=="undefined")

{

  if (localStorage.clickcount)

  {

  localStorage.clickcount=Number(localStorage.clickcount)+1;

  }

  else

  {

  localStorage.clickcount=1;

  }

  document.getElementById("result").innerHTML=" 你已经点击了按钮 " + localStorage.clickcount + " 次 ";

}

else

{

document.getElementById("result").innerHTML="对不起,您的浏览器不支持 web 存储。";

}

Copy after login

sessionStorage object

sessionStorage stores data for a session. The data will be deleted when the user closes the browser window

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

   if(typeof(Storage)!=="undefined")

    {

        if (sessionStorage.clickcount)

        {

            sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;

        }

        else

        {

            sessionStorage.clickcount=1;

        }

        document.getElementById("result").innerHTML="在这个会话中你已经点击了该按钮 " + sessionStorage.clickcount + " 次 ";

    }

    else

    {

        document.getElementById("result").innerHTML="抱歉,您的浏览器不支持 web 存储";

    }

Copy after login

Simple website list program

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

 <div style="border: 2px dashed #ccc;width:320px;text-align:center;">     <label for="sitename">网站名(key):</label>  <input type="text" id="sitename" name="sitename" class="text"/>  <br/>  <label for="siteurl">网 址(value):</label>  <input type="text" id="siteurl" name="siteurl"/>  <br/>  <input type="button" onclick="save()" value="新增记录"/>  <hr/>  <label for="search_phone">输入网站名:</label>  <input type="text" id="search_site" name="search_site"/>  <input type="button" onclick="find()" value="查找网站"/>  <p id="find_result"><br/></p>  </div>  <br/>  <div id="list">  </div>  <script>// 载入所有存储在localStorage的数据    loadAll();     

        //保存数据  function save(){  var siteurl = document.getElementById("siteurl").value;  var sitename = document.getElementById("sitename").value;  

        localStorage.setItem(sitename, siteurl);

        alert("添加成功");

    }//查找数据  function find(){  var search_site = document.getElementById("search_site").value;  var sitename = localStorage.getItem(search_site);  var find_result = document.getElementById("find_result");  

        find_result.innerHTML = search_site + "的网址是:" + sitename;  

    }//将所有存储在localStorage中的对象提取出来,并展现到界面上function loadAll(){  var list = document.getElementById("list");  if(localStorage.length>0){  var result = "<table border=&#39;1&#39;>";  

            result += "<tr><td>网站名</td><td>网址</td></tr>";  for(var i=0;i<localStorage.length;i++){  var sitename = localStorage.key(i);  var siteurl = localStorage.getItem(sitename);  

                result += "<tr><td>"+sitename+"</td><td>"+siteurl+"</td></tr>";  

            }  

            result += "</table>";  

            list.innerHTML = result;  

        }else{  

            list.innerHTML = "数据为空……";  

        }  

    }      </script>

Copy after login

Run Result:

JSON.stringify

##  Store object data and convert the object to a string

1

2

var site = new Object;

...var str = JSON.stringify(site); // 将对象转换为字符串

Copy after login

JSON.parse

Convert the string into a JSON object

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

 <div style="border: 2px dashed #ccc;width:320px;text-align:center;"><label for="keyname">别名(key):</label>  <input type="text" id="keyname" name="keyname" class="text"/>  <br/>  <label for="sitename">网站名:</label>  <input type="text" id="sitename" name="sitename" class="text"/>  <br/>  <label for="siteurl">网 址:</label>  <input type="text" id="siteurl" name="siteurl"/>  <br/>  <input type="button" onclick="save()" value="新增记录"/>  <hr/>  <label for="search_phone">输入别名(key):</label>  <input type="text" id="search_site" name="search_site"/>  <input type="button" onclick="find()" value="查找网站"/>  <p id="find_result"><br/></p>  </div>  <br/>  <div id="list">  </div>  <script>//保存数据  function save(){  var site = new Object;

        site.keyname = document.getElementById("keyname").value;

        site.sitename = document.getElementById("sitename").value;  

        site.siteurl = document.getElementById("siteurl").value;var str = JSON.stringify(site); // 将对象转换为字符串        localStorage.setItem(site.keyname,str);  

        alert("保存成功");

    }  //查找数据  function find(){  var search_site = document.getElementById("search_site").value;  var str = localStorage.getItem(search_site);  var find_result = document.getElementById("find_result");var site = JSON.parse(str);  

        find_result.innerHTML = search_site + "的网站名是:" + site.sitename + ",网址是:" + site.siteurl;  

    }  

    //将所有存储在localStorage中的对象提取出来,并展现到界面上// 确保存储的 keyname 对应的值为转换对象,否则JSON.parse会报错function loadAll(){  var list = document.getElementById("list");  if(localStorage.length>0){  var result = "<table border=&#39;1&#39;>";  

            result += "<tr><td>别名</td><td>网站名</td><td>网址</td></tr>";  for(var i=0;i<localStorage.length;i++){ var keyname = localStorage.key(i);  var str = localStorage.getItem(keyname);  var site = JSON.parse(str);  

                result += "<tr><td>"+site.keyname+"</td><td>"+site.sitename+"</td><td>"+site.siteurl+"</td></tr>";  

            }  

            result += "</table>";  

            list.innerHTML = result;  

        }else{  

            list.innerHTML = "数据为空...";  

        }  

    }  </script>

Copy after login
The above is JSON. The result of stringify conversion

The following is the result of JSON.parse conversion

The above is the detailed content of How to use HTML5-Web storage?. For more information, please follow other related articles on the PHP Chinese website!

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 AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

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)

Huawei will launch innovative MED storage products next year: rack capacity exceeds 10 PB and power consumption is less than 2 kW Huawei will launch innovative MED storage products next year: rack capacity exceeds 10 PB and power consumption is less than 2 kW Mar 07, 2024 pm 10:43 PM

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 skills: how to encrypt and store data Vue3+TS+Vite development skills: how to encrypt and store data Sep 10, 2023 pm 04:51 PM

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 does h5 mean? What does h5 mean? Aug 02, 2023 pm 01:52 PM

H5 refers to HTML5, the latest version of HTML. H5 is a powerful markup language that provides developers with more choices and creative space. Its emergence promotes the development of Web technology, making the interaction and effect of web pages more Excellent, as H5 technology gradually matures and becomes popular, I believe it will play an increasingly important role in the Internet world.

Git installation process on Ubuntu Git installation process on Ubuntu Mar 20, 2024 pm 04:51 PM

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

What are web standards? What are web standards? Oct 18, 2023 pm 05:24 PM

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

How to correctly use sessionStorage to protect sensitive data How to correctly use sessionStorage to protect sensitive data Jan 13, 2024 am 11:54 AM

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.

what does web mean what does web mean Jan 09, 2024 pm 04:50 PM

The web is a global wide area network, also known as the World Wide Web, which is an application form of the Internet. The Web is an information system based on hypertext and hypermedia, which allows users to browse and obtain information by jumping between different web pages through hyperlinks. The basis of the Web is the Internet, which uses unified and standardized protocols and languages ​​to enable data exchange and information sharing between different computers.

See all articles