This article mainly introduces the relevant information of Web Storage of HTML5 local storage in detail. How Web Storage uses JSON to store multiple data. Interested friends can refer to it.
Appears in HTML5 Previously, if developers needed to store a small amount of data on the client, they could only do so through cookies. However, cookies had several shortcomings:
•The size of cookies under each domain name was limited to 4KB.
•The cookie will be included in every http request, which will cause duplicate data to be sent.
•Cookies are not encrypted during network transmission, which poses security risks.
The Web storage function has been added to HTML5. Web Storage is officially recommended to be 5MB for each website. It can store more data than cookies and has more powerful functions than cookies. Web Storage is now supported by major browsers such as Firefox, Opera, Chrome, and Safari.
Introduction to Web Storage
Web Storage is divided into Session Storage and Local Storage:
Session Storage: Similar to session, the data lifetime saved by Session Storage is the same as the Session period. When the user Session ends, the data saved by Session Storage will disappear.
Local Storage: The data saved by Local Storage is always local, and unless the user or program explicitly knows it, the data will exist consistently.
The window object provides two attributes, sessionStorage and localStorage, which represent Session Storage and Local Storage respectively. The functions and usage of these two are almost the same, except that the lifetime of data they save is different. Storage provides the following properties and methods (taking localStorage as an example):
•localStorage.length: Get the number of key-value pairs;
•localStorage.key(index): Get the key of the index index ;
•localStorage.getItem(key): Get the value corresponding to the specified key;
•localStorage.setItem(key, value): Save the specified key-value pair;
•localStorage.removeItem(key) : Delete the key-value pairs corresponding to the specified key;
•localStorage.clear(): Delete all key-value pairs.
It should be noted that both key and value must be strings. In other words, the web Storage API can only operate on strings. Then for some data that is not a string, we can convert it into a string format through JSON and other methods before operating it.
Web Storage uses JSON to store multiple data
We use a small program to familiarize ourselves with the basic usage of related properties and methods:
•Enter The student's basic information (including student ID, name, grade, gender) is stored in local storage with the student ID as the key value;
• Query the student's basic information through the student ID;
• Display all students information;
First we design the HTML page
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>HTML本地存储之web storage</title> <style type="text/css"> #content{ border: 1px solid #3D19DD; width:600px; text-align:center; padding: 10px 0; margin: 0 auto; } #content input{ margin-top: 10px; } </style> </head> <body> <p id="content"> <label for="user_num">学号:</label> <input type="text" id="user_num" name="user_num" /> <br/> <label for="user_name">姓名:</label> <input type="text" id="user_name" name="user_name" /> <br/> <label for="grade">年级:</label> <input type="text" id="grade" name="grade"/> <br/> <label for="sex">性别:</label> <input type="text" id="sex" name="sex"/> <br/> <input type="button" onclick="save()" value="添加名单"/> <hr/> <label for="search_num">输入学号:</label> <input type="text" id="search_num" name="search_num"/> <input type="button" onclick="find()" value="查找学生信息"/> <p id="find_result"><br/></p> <hr/> <input type="button" onclick="show()" value="显示所有"> <p id="list"> </p> </p> <br /> </body> </html>
Use JS to save student information to local storage. Through analysis, we find the student information that needs to be saved. Including multiple fields, at this time, we can use JSON's stringify() method to convert the complex object into a string and store it in Web Storage; when reading from Web Storage, we can use JSON's parse() method to Convert to JSON object:
function save(){ var user_num = document.getElementById("user_num").value; var user_nameElement = document.getElementById("user_name").value; var gradeElement = document.getElementById("grade").value; var sexElement = document.getElementById("sex").value; var msg = { user_name: user_nameElement, grade: gradeElement, sex: sexElement, }; localStorage.setItem(user_num,JSON.stringify(msg)); }
We store three pieces of student information in localStorage and view the storage information in localStorage:
Use JS When searching for student information by student ID, you need to pay attention to the value taken out as a JSON string, which needs to be converted into a JSON object through the JSON parse() method. The code is as follows:
function find(){ var user_num = document.getElementById("search_num").value; var str = localStorage.getItem(user_num); var msg = JSON.parse(str); var find_result = document.getElementById("find_result"); find_result.innerHTML = "学号为:"+user_num+"的基本信息: 姓名:"+msg.user_name + ",年级:" + msg.grade+",性别:"+msg.sex; }
Similarly, display all students When receiving information, you also need to convert the extracted value string into a JSON object:
function show(){ var list = document.getElementById("list"); if(localStorage.length>0){ var result = "<table border='1' style='width:300px; margin:0 auto;'>"; result += "<tr><td>学号</td><td>姓名</td><td>年级</td><td>性别</td></tr>"; for(var i=0;i<localStorage.length;i++){ var user_num = localStorage.key(i); var str = localStorage.getItem(user_num); var msg = JSON.parse(str); result += "<tr><td>"+user_num+"</td><td>"+msg.user_name+"</td><td>"+msg.grade+"</td><td>"+msg.sex+"</td></tr>"; } result += "</table>"; list.innerHTML = result; }else{ list.innerHTML = "当前还没有数据"; } }
The final rendering is as follows:
Web Storage stores pictures
We have mentioned before that local storage only supports string access, so what we have to do is to convert the picture into a Data URI. One way to achieve this is to use the canvas element to load images. Then you can read the image from the canvas as a Data URI.
The function to save the image is as follows:
function setImg(key,src){ var img = document.createElement('img'); //当图片加载完成的时候触发回调函数 img.addEventListener("load",function(){ var imgCanvas = document.createElement("canvas"), imgContext = imgCanvas.getContext("2d"); //确保canvas元素大小和图片的尺寸一致 imgCanvas.width = this.width; imgCanvas.height = this.height; //渲染图片到canvas中 imgContext.drawImage(this,0,0,this.width,this.height); //用data url的形式取出 img.crossOrigin = "*"; //防止跨域取照片出错 var imgAsDataURL = imgCanvas.toDataURL("image/png"); //保存到本地存储中 try{ localStorage.setItem(key, imgAsDataURL); } catch(e){ alert("保存失败!请重试。。。"); } }, false); img.src = src; }
This function receives two parameters, one is the key value, and the other is the path of the image, which is saved through setImg("img1","1.jpg") Picture to localStorage, we can check the storage situation of Local Storage:
The code function to obtain and display is as follows:
function getImg(key){ var srcStr = localStorage.getItem(key); var imgObj = document.createElement('img'); imgObj.src = srcStr; document.body.appendChild(imgObj); }
This function only receives One parameter: the key value of the image that needs to be found:
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
The above is the detailed content of HTML5 local storage Web Storage. For more information, please follow other related articles on the PHP Chinese website!

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.


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

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
