Home  >  Article  >  Web Front-end  >  HTML5 local storage Web Storage

HTML5 local storage Web Storage

不言
不言Original
2018-06-14 10:07:401734browse

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=&#39;1&#39; style=&#39;width:300px; margin:0 auto;&#39;>";     
            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(&#39;img&#39;);   
        //当图片加载完成的时候触发回调函数 
        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(&#39;img&#39;);   
        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:

HTML5 local storage IndexedDB

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!

Statement:
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