Table of Contents
Cookie
Web Storage
Easy to use
API
Example
Home Web Front-end H5 Tutorial HTML5 client data storageWeb Storage—localStorage and sessionStorage

HTML5 client data storageWeb Storage—localStorage and sessionStorage

Feb 27, 2017 pm 03:25 PM


HTML5 provides a new method of storing data on the client side Web Storage
Similar to Cookie in HTML4
But it is much more powerful

Cookie

Let’s briefly review the cookies used before

Cookies store data on the user’s device. The amount of data stored is small, only 4KB
Yes Detect whether cookies are enabled through navigator.cookieEnabled

  • Set cookies document.cookie = 'key=value';

  • Get cookie document.cookie;

  • Delete cookie document.cookie = "key=value;max-age=0";

  • Set max-age storage perioddocument.cookie = "key=value;max-age=1000"; // 1000 seconds

  • Set expires storage period

1

2

var timestamp = (new Date()).getTime() + 10000;var expires = new Date(timestamp).toGMTString();

//或toUTCStringdocument.cookie = "key=value;expires="+expires;

Copy after login
  • Get specific cookie value

1

2

3

4

5

6

7

8

9

10

11

12

13

function getCookie(name) {

    var name = name + "=";   

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

    for(var i = 0; i < ary.length; i++){       

    var c = ary[i];       

    while (c.charAt(0) == &#39; &#39;){

          c = c.substring(1);

        }       

        if (c.indexOf(name) != -1){         

        return c.substring(name.length, c.length);

        }

    }    return "";

}

Copy after login

Web Storage

Web Storage is divided into two types
localStorage and sessionStorage
The difference is:

  • localStorage stores permanent data unless manually deleted

  • sessionStorage stores temporary data and will disappear when the window is closed

Easy to use

Web Storage can only store string data
I think they can be understood as JSON
The usage methods are similar, taking localStorage as an example

1

2

3

4

localStorage.name = &#39;payen&#39;;

localStorage.info = JSON.stringify({name: &#39;payen&#39;, age: 20});

console.log(localStorage.name);

console.log(JSON.parse(localStorage.info));

Copy after login

The name of the data to be stored is the attribute name of localStorage
Ordinary strings can be stored normally That’s it
Object data can be converted to string format using JSON.stringify()
When used, JSON.parse() can be used to convert it back to object format
(If the object is stored directly, it will Forced to be converted into a string "[object Object]")


To delete the data, just delete it

1

delete localStorage.name;delete localStorage.info;

Copy after login

If you do not delete it, the data in localStorage will always exist for you. The browser

API

localStorage and sessionStorage also provide a simple API
Similar to a client database
(APIs are the same)
Commonly used There are the following:

  • Save data setItem(key, value)

  • Read data getItem(key)

  • Delete a single data removeItem(key)

  • Clear all data clearItem()

  • Get the data index key(index)

Example

Through this, we can write a simple address book

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<p id="container">

    <br>

    <label for="username">姓名:</label>

    <input type="text" id="username" name="username">

    <br>

    <label for="mobilephone">手机:</label>

    <input type="text" id="mobilephone" name="mobilephone">

    <br><br>

    <input type="button" onclick="add()" id="add" value="增加联系人">

    <br><br>

    <hr>

    <label for="search">输入姓名:</label>

    <input type="text" id="search" name="search">

    <br><br>

    <input type="button" onclick="find()" id="find" value="查找手机号">

    <p id="result"><br></p></p>

Copy after login

1

2

3

4

#container {   

border: 2px solid gray;   

width: 320px;   

text-align:center;}

Copy after login

HTML5 client data storageWeb Storage—localStorage and sessionStorage

##It is implemented in JavaScript These two functions

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

var user = document.getElementById(&#39;username&#39;),

    phone = document.getElementById(&#39;mobilephone&#39;),

    search = document.getElementById(&#39;search&#39;),

    result = document.getElementById(&#39;result&#39;);var add = function(){

    var u = user.value,

        p = phone.value,

        l = localStorage.length;    if(u !== &#39;&#39; && p !== &#39;&#39;){

        localStorage.setItem(u, p);

        user.value = &#39;&#39;;

        phone.value = &#39;&#39;;

        alert(&#39;添加成功&#39;);

    }

};var find = function(){

    var s = search.value,

        r = localStorage.getItem(s);    if(s !== &#39;&#39; && r){

        result.innerHTML = r;

    }

};

Copy after login

HTML5 client data storageWeb Storage—localStorage and sessionStorage

Enter the name and mobile phone number to add a contact

Then enter the contact name below and we can find the mobile phone number

HTML5 client data storageWeb Storage—localStorage and sessionStorage


Of course this address book is very simple

You can also add it to display all the information in the address book
Delete contact function, etc.

Cookies and Web Storage Difference

Finally let’s talk about the difference between Html5’s Web Storage and Html4’s cookie

FeaturesCookieWeb StorageLife cycle is generally generated by the server and sets the time; generated by the browser, it is closed by default and the browser failslocal : Save permanently if not cleared; session: Close the page or the browser is invalidData size4KBOfficial recommendation 5MBCommunicationCarried in the HTTP header (excessive use may cause performance problems)Only stored in the browser, does not participate in communicationUsingThe native interface is not friendly and needs to be encapsulated manuallyThe native interface is friendly
The above is the HTML5 client data storage Web Storage—localStorage and sessionStorage content. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



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)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles