Web Storage for HTML5 Local Storage

Source: Internet
Author: User
Tags sessionstorage

Web Storage is a very important feature introduced by HTML5. It can store data locally on the client, similar to the cookie of HTML4. However, it has more powerful functions than cookies, the cookie size is limited to 4 kb, and the Web Storage officially recommends 5 MB for each website.

There are two types of Web Storage:


• SessionStorage
• LocalStorage

It can be clearly indicated from the literal meaning that sessionStorage saves the data in the session, and the browser closes, while localStorage keeps saving the data locally on the client;

The APIs available for both sessionStorage and localStorage are the same. Common APIs are as follows (using localStorage as an example ):


• Save data: localStorage. setItem (key, value );
• Read data: localStorage. getItem (key );
• Delete a single data: localStorage. removeItem (key );
• Delete all data: localStorage. clear ();
• Obtain the key of an index: localStorage. key (index );

As shown above, both the key and value must be strings. In other words, the web Storage API can only operate strings.

Next, we will develop a simple address book applet through Web Storage to demonstrate how to use related APIs. We will implement the following functions:


1. Enter a contact. The contact has two fields: Name and mobile phone number. The mobile phone number is used as the key and stored in localStorage;
2. Search for the host based on the phone number;
3. list all currently saved contacts;

First, prepare a simple HTML page, as shown below:


[Html]
01. <! Doctype html>
02. 03. 04. <meta charset = "UTF-8"/>
05. <title> Web Storage for HTML5 local Storage </title>
06. 07. <body>
08. <div style = "border: 2px dashed # ccc; width: 320px; text-align: center;">
09. <label for = "user_name"> name: </label>
10. <input type = "text" id = "user_name" name = "user_name" class = "text"/>
11. <br/>
12. <label for = "mobilephone"> mobile phone: </label>
13. <input type = "text" id = "mobilephone" name = "mobilephone"/>
14. <br/>
15. <input type = "button" onclick = "save ()" value = "add record"/>
16. 17. <label for = "search_phone"> enter the mobile phone number: </label>
18. <input type = "text" id = "search_phone" name = "search_phone"/>
19. <input type = "button" onclick = "find ()" value = ""/>
20. <p id = "find_result"> <br/> </p>
21. </div>
22. <br/>
23. <div id = "list">
24. </div>
25. </body>
26. <! Doctype html>
<Html>
<Head>
<Meta charset = "UTF-8"/>
<Title> Web Storage for HTML5 local Storage </title>
</Head>
<Body>
<Div style = "border: 2px dashed # ccc; width: 320px; text-align: center;">
<Label for = "user_name"> name: </label>
<Input type = "text" id = "user_name" name = "user_name" class = "text"/>
<Br/>
<Label for = "mobilephone"> mobile phone: </label>
<Input type = "text" id = "mobilephone" name = "mobilephone"/>
<Br/>
<Input type = "button" onclick = "save ()" value = "add record"/>
<Hr/>
<Label for = "search_phone"> enter the mobile phone number: </label>
<Input type = "text" id = "search_phone" name = "search_phone"/>
<Input type = "button" onclick = "find ()" value = ""/>
<P id = "find_result"> <br/> </p>
</Div>
<Br/>
<Div id = "list">
</Div>
</Body>
</Html> the page is displayed as follows:

 

To save contacts, simply implement the following JS method:


[Javascript]
01. // save data
02. function save (){
03. var mobilephone = document. getElementById ("mobilephone"). value;
04. var user_name = document. getElementById ("user_name"). value;
05. localStorage. setItem (mobilephone, user_name );
06 .}
// Save data
Function save (){
Var mobilephone = document. getElementById ("mobilephone"). value;
Var user_name = document. getElementById ("user_name"). value;
LocalStorage. setItem (mobilephone, user_name );
} To find the host, implement the following JS method:


[Javascript]
01. // search for Data
02. function find (){
03. var search_phone = document. getElementById ("search_phone"). value;
04. var name = localStorage. getItem (search_phone );
05. var find_result = document. getElementById ("find_result ");
06. The host of find_result.innerHTML = search_phone + "is:" + name;
07 .}
// Search for Data
Function find (){
Var search_phone = document. getElementById ("search_phone"). value;
Var name = localStorage. getItem (search_phone );
Var find_result = document. getElementById ("find_result ");
The host for find_result.innerHTML = search_phone + "is:" + name;
}

To display all the saved contact information, use the localStorage. key (index) method as follows:


[Javascript]
01. // extract all objects stored in localStorage and display them on the Interface
02. function loadAll (){
03. var list = document. getElementById ("list ");
04. if (localStorage. length> 0 ){
05. var result = "<table border = '1'> ";
06. result + = "<tr> <td> name </td> <td> mobile phone number </td> </tr> ";
07. for (var I = 0; I <localStorage. length; I ++ ){
08. var mobilephone = localStorage. key (I );
09. var name = localStorage. getItem (mobilephone );
10. result + = "<tr> <td>" + name + "</td> <td>" + mobilephone + "</td> </tr> ";
11 .}
12. result + = "</table> ";
13. list. innerHTML = result;
14.} else {
15. list. innerHTML = "the current data is empty. Please join the contact ";
16 .}
17 .}
// Extract all objects stored in localStorage and display them on the Interface
Function loadAll (){
Var list = document. getElementById ("list ");
If (localStorage. length> 0 ){
Var result = "<table border = '1'> ";
Result + = "<tr> <td> name </td> <td> mobile phone number </td> </tr> ";
For (var I = 0; I <localStorage. length; I ++ ){
Var mobilephone = localStorage. key (I );
Var name = localStorage. getItem (mobilephone );
Result + = "<tr> <td>" + name + "</td> <td>" + mobilephone + "</td> </tr> ";
}
Result + = "</table> ";
List. innerHTML = result;
} Else {
List. innerHTML = "the current data is empty. Please join the contact ";
}
}
Q: In the above demo, there are only two fields, name and mobile phone number. If you want to store more contact information, such as the company name and home address, how can this problem be achieved? Isn't Web Storage only capable of processing strings? In this case, you can use the stringify () method of JSON to convert complex objects into strings and store them in Web Storage. when reading from Web Storage, you can use the JSON parse () the method is then converted to a JSON object;

The following is a simple demonstration of adding a contact with the company property to save the JS Code:


[Javascript]
01. // save data
02. function save (){
03. var contact = new Object;
04. contact. user_name = document. getElementById ("user_name"). value;
05. contact. mobilephone = document. getElementById ("mobilephone"). value;
06. contact. company = document. getElementById ("company"). value;
07. var str = JSON. stringify (contact );
08. localStorage. setItem (contact. mobilephone, str );
09. loadAll ();
10 .}
11. // extract all objects stored in localStorage and display them on the Interface
12. function loadAll (){
13. var list = document. getElementById ("list ");
14. if (localStorage. length> 0 ){
15. var result = "<table border = '1'> ";
16. result + = "<tr> <td> name </td> <td> mobile phone </td> <td> company </td> </tr> ";
17. for (var I = 0; I <localStorage. length; I ++ ){
18. var mobilephone = localStorage. key (I );
19. var str = localStorage. getItem (mobilephone );
20. var contact = JSON. parse (str );
21. result + = "<tr> <td>" + contact. user_name + "</td> <td>" + contact. mobilephone + "</td> <td>" + contact. company + "</td> </tr> ";
22 .}
23. result + = "</table> ";
24. list. innerHTML = result;
25.} else {
26. list. innerHTML = "the current data is empty. Please join the contact ";
27 .}
28 .}
// Save data
Function save (){
Var contact = new Object;
Contact. user_name = document. getElementById ("user_name"). value;
Contact. mobilephone = document. getElementById ("mobilephone"). value;
Contact. company = document. getElementById ("company"). value;
Var str = JSON. stringify (contact );
LocalStorage. setItem (contact. mobilephone, str );
LoadAll ();
}
// Extract all objects stored in localStorage and display them on the Interface
Function loadAll (){
Var list = document. getElementById ("list ");
If (localStorage. length> 0 ){
Var result = "<table border = '1'> ";
Result + = "<tr> <td> name </td> <td> mobile phone </td> <td> company </td> </tr> ";
For (var I = 0; I <localStorage. length; I ++ ){
Var mobilephone = localStorage. key (I );
Var str = localStorage. getItem (mobilephone );
Var contact = JSON. parse (str );
Result + = "<tr> <td>" + contact. user_name + "</td> <td>" + contact. mobilephone + "</td> <td>" + contact. company + "</td> </tr> ";
}
Result + = "</table> ";
List. innerHTML = result;
} Else {
List. innerHTML = "the current data is empty. Please join the contact ";
}
}

 

 

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.