Html5 guide-5. Use web storage to store key-value pairs

Source: Internet
Author: User
Tags sessionstorage

Comments: The content of this lesson is to introduce web storage and use it to store key-value pair data in a browser. The function is the same as the previous cookie, but it is better, if you are more interested in the stored data, you can learn about it. In this lesson, we will introduce web storage and use it to store key-value pairs in your browser, the function is the same as the previous cookie, but it is better to store more data. There are two types of web storage: local storage and session storage. They use the same implementation mechanism, but the visibility and lifecycle are different.
1. Use local storage
We use the localStorage object to access local storage. It returns the Storage object, which is used to store the data of key-value pairs. It has the following attributes and methods:
Clear (): clear the stored key-value pair data;
GetItem (<key>): obtains the value through the key;
Key (<index>): Obtain the key value through the index;
Length: Number of Return key-value pairs;
RemoveItem (<key>): removes the specified data using the key;
SetItem (<key >,< value>): adds a key-value pair. If the key-value pair of the specified key exists, the update operation is performed;
[<Key>]: obtains the specified value by using the key as the array subscript.
The Storage object allows us to store key-value pairs in string format. The key is unique, meaning that when we use the setItem method to add a key-value pair, if the key value already exists, the update operation is performed. Let's take a look at the following example:

The Code is as follows:
<! Doctype html>
<Html>
<Head>
<Title> Example </title>
<Style>
Body> * {float: left ;}
Table {border-collapse: collapse; margin-left: 50px ;}
Th, td {padding: 4px ;}
Th {text-align: right ;}
Input {border: thin solid black; padding: 2px ;}
Label {min-width: 50px; display: inline-block; text-align: right ;}
# Countmsg, # buttons {margin-left: 50px; margin-top: 5px; margin-bottom: 5px ;}
</Style>
</Head>
<Body>
<Div>
<Div>
<Label> Key: </label> <input id = "key" placeholder = "Enter Key"/> </div>
<Div>
<Label> Value: </label> <input id = "value" placeholder = "Enter Value"/> </div>
<Div id = "buttons">
<Button id = "add"> Add </button>
<Button id = "clear"> Clear </button>
</Div>
<P id = "countmsg"> There are <span id = "count"> </span> items </p>
</Div>
<Table id = "data" border = "1">
<Tr>
<Th> Item Count: </th>
<Td id = "count">-</td>
</Tr>
</Table>
<Script>
DisplayData ();
Var buttons = document. getElementsByTagName ('click ');
For (var I = 0; I <buttons. length; I ++ ){
Buttons [I]. onclick = handleButtonPress;
}
Function handleButtonPress (e ){
Switch (e.tar get. id ){
Case 'add ':
Var key = document. getElementById ('key'). value;
Var value = document. getElementById ('value'). value;
LocalStorage. setItem (key, value );
Break;
Case 'clear ':
LocalStorage. clear ();
Break;
}
DisplayData ();
}
Function displayData (){
Var tableElement = document. getElementById ('data ');
TableElement. innerHTML = '';
Var itemCount = localStorage. length;
Document. getElementById ('Count'). innerHTML = itemCount;
For (var I = 0; I <itemCount; I ++ ){
Var key = localStorage. key (I );
Var val = localStorage. getItem (key );
TableElement. innerHTML + = '<tr> <th>' + key + ': </th> <td>' + val + '</td> </tr> ';
}
}
</Script>
</Body>
</Html>

Let's look at the running results:


The browser cannot delete the data we created through localStorage unless you delete it.
2. Monitor Storage events
Data stored through local storage is visible to documents of the same source. For example, you can open two chrome browsers to access the same url address, the local storage created on any page is also visible to another page. However, if you use another browser (such as firefox) to open the same url address, local storage is invisible because they are different from each other. The Storage event is used to listen for changes to the storage content. Let's see what attributes it contains:
Key: return the changed key value;
OldValue: returns the value before the key value is changed;
NewValue: return the new value that changes the key value;
Url: changed url address;
StorageArea: return the changed Storage object (whether it is local storage or session storage ).
The following is an example:

The Code is as follows:
<! Doctype html>
<Html>
<Head>
<Title> Storage </title>
<Style>
Table {border-collapse: collapse ;}
Th, td {padding: 4px ;}
</Style>
</Head>
<Body>
<Table id = "data" border = "1">
<Tr>
<Th> key </th>
<Th> oldValue </th>
<Th> newValue </th>
<Th> url </th>
<Th> storageArea </th>
</Tr>
</Table>
<Script>
Var tableElement = document. getElementById ('data ');
Window. onstorage = function (e ){
Var row = '<tr> ';
Row + = '<td>' + e. key + '</td> ';
Row + = '<td>' + e. oleValue + '</td> ';
Row + = '<td>' + e. newValue + '</td> ';
Row + = '<td>' + e. url + '</td> ';
Row + = '<td>' + (e. storageArea = localStorage) + '</td> </tr> ';
TableElement. innerHTML + = row;
}
</Script>
</Body>
</Html>

We add and delete the storage data in Example 1, which is displayed on the page of Example 2. Example 2 runs normally in chrome, firefox does not respond, and other browsers do not test.
Running result:


3. Use session storage
Session storage is used in the same way as local storage, but its access is only limited to the current page. When the page is closed, it disappears. We access it through sessionStorage.

The Code is as follows:
<! Doctype html>
<Html>
<Head>
<Title> Example </title>
<Style>
Body> * {float: left ;}
Table {border-collapse: collapse; margin-left: 50px ;}
Th, td {padding: 4px ;}
Th {text-align: right ;}
Input {border: thin solid black; padding: 2px ;}
Label {min-width: 50px; display: inline-block; text-align: right ;}
# Countmsg, # buttons {margin-left: 50px; margin-top: 5px; margin-bottom: 5px ;}
</Style>
</Head>
<Body>
<Div>
<Div>
<Label> Key: </label> <input id = "key" placeholder = "Enter Key"/> </div>
<Div>
<Label> Value: </label> <input id = "value" placeholder = "Enter Value"/> </div>
<Div id = "buttons">
<Button id = "add"> Add </button>
<Button id = "clear"> Clear </button>
</Div>
<P id = "countmsg"> There are <span id = "count"> </span> items </p>
</Div>
<Table id = "data" border = "1">
<Tr>
<Th> Item Count: </th>
<Td id = "count">-</td>
</Tr>
</Table>
<Iframe src = "storage.html" width = "500" height = "175"> </iframe>
<Script>
DisplayData ();
Var buttons = document. getElementsByTagName ("button ");
For (var I = 0; I <buttons. length; I ++ ){
Buttons [I]. onclick = handleButtonPress;
}
Function handleButtonPress (e ){
Switch (e.tar get. id ){
Case 'add ':
Var key = document. getElementById ("key"). value;
Var value = document. getElementById ("value"). value;
SessionStorage. setItem (key, value );
Break;
Case 'clear ':
SessionStorage. clear ();
Break;
}
DisplayData ();
}
Function displayData (){
Var tableElement = document. getElementById ('data ');
TableElement. innerHTML = '';
Var itemCount = sessionStorage. length;
Document. getElementById ('Count'). innerHTML = itemCount;
For (var I = 0; I <itemCount; I ++ ){
Var key = sessionStorage. key (I );
Var val = sessionStorage. getItem (key );
TableElement. innerHTML + = "<tr> <th>" + key + ": </th> <td>" + val + "</td> </tr> ";
}
}
</Script>
</Body>
</Html>

Running Effect:


If you make any changes in Example 3, the page in example 2 will not change.
Summary:
SessionStorage is used to locally store data in a session. The data can be accessed only on pages in the same session. When the session ends, the data is also destroyed. SessionStorage is not a persistent local storage, but a session-level storage.
LocalStorage is used for persistent local storage. Unless data is actively deleted, the data will never expire.
Difference between web storage and cookie: the concept of Web Storage is similar to that of cookie. The difference is that it is designed for larger storage capacity. The Cookie size is limited, and the Cookie will be sent every time you request a new page. This will result in a waste of bandwidth. In addition, the cookie also needs to specify the scope, cross-origin calls are not allowed. In addition, Web Storage has methods such as setItem, getItem, removeItem, and clear. Unlike cookies, front-end developers need to encapsulate setCookie and getCookie by themselves. In addition, each domain (including subdomains) of web storage has an independent storage space, and each storage space is completely independent, so it will not cause data confusion.
However, cookies are indispensable: cookies interact with servers and exist as part of HTTP specifications. Web Storage is only used to "Store" data locally.
Source code download

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.