Article 17 of study notes in Javascript authoritative guide: new BOM (1) -- client Storage implementation)

Source: Internet
Author: User
Tags http cookie sessionstorage

The data constitutes the actual content of the web site. The data is diverse and can be an independent file, a database file, or a database server. Currently, HTML 5 BOM allows large-scale data storage on the client: web storage and Web SQL database storage.


I. Web storage Overview

Web storage is a secure way to store and use data using key/value pairs in the form of strings. The difference between Web storage and HTTP Cookie is:

1. Different capacities: Web storage capacity is large, safer, and easier to use; Cookie storage capacity is limited

2. storage persistence is also different: Web storage uses a browser to permanently store data of a reasonable size. cookies do not support permanent data storage.


Ii. Web storage type

1. There are two types of data stored on the client:

1.1 localStorage: Local Storage, no time limit for data storage.

1.2 sessionStorage: Session storage, for data storage during a session.


2. permanently store data on the client-create Storage

The data stored in localStorage has no time limit and can be used permanently.

Var oStorage = window. localStorage; // return a Storage object. You can call the corresponding method and attribute oStorage. book ="Javascript authoritative guide"; // Add a key value // window. localStorage. book ="Javascript authoritative guide"; // View the key value if (oStorage. book) {alert (oStorage. book);} else {alert (" the key value does not exist ");}

Is the running result of google, the intermediate figure is the data stored by google local storage (ctrl + shift + I view), is the data stored by local storage in FF (ctrl + shift + k view)


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + pgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20140613/20140613091941141.jpg" alt = "\">

Because the earlier FF does not display localStorage, The globalstorage attribute is provided to create local storage for the specified domain. You can use the following code to achieve compatibility:

Var strDomain = "127.0.0.1 ";

Var oStorage = window. localStorage? Window. localStorage: window. globalStorage [strDomain];

Var strDomain = "127.0.0.1"; try {var oStorage = window. localStorage? Window. localStorage: window. globalStorage [strDomain]; if (oStorage. visitorCount) {oStorage. visitorCount = parseInt (oStorage. visitorCount, 10) + 1;} else {oStorage. visitorCount = 1;} document. write ("welcome" + oStorage. visitorCount + "<\/span> times of access");} catch (err) {alert (err. message? Err. message: err. toString ());}

Running results in Google

After the browser is closed, localStorage still exists, but sessionStorage only exists during the session period.


3. Store data during the session --- create sessionStorage

SessionStorage stores data for a Session. When the user closes the browser, the data is deleted. Window. sessionStorage returns the session storage region created during the current page session period. As long as the browser is not closed, the page is reloaded or restored, or the session is redirected to another page from the current page, the session persists.

You can use the Storage object returned by the window. sessionStorage attribute to call object methods and properties.

<script type="text/javascript">var oField = document.getElementById("myName");var oStorage = window.sessionStorage;if(oStorage.myNameValue){    oField.value = oStorage.myNameValue;}</script>
Result:

If the user input is incorrect and the page is returned, the data is restored.


Iii. Storage Interface

HTML5 standardizes the WindowSessionStorage and WindowLocalStorage interfaces, which correspond to the SessionStorage and Localstorage attributes of sessionStorage and localStorage respectively. Both return Storage objects.

1. oStorage. length attribute: Get the number of key/value pairs.

2. oStorage. key (index): Obtain the key name based on the index. The return key name is a string or an empty string. PS: after a new key-value pair is added, the index changes.

3. oStorage. getItem (skey): obtain the corresponding key value based on the key name skey. If the key does not exist, null is returned.

PS: Do not read or write keys defined in the secure URL environment (HTTP.


4. oStorage. clear (): clears all key/value pairs, including buckets.

5. oStorage. removeItem (skey): deletes a specified key-value pair. The skey is the specified key name and can be blank.

6. oStorage. setItem (skey, svalue): Add or update a key-value pair.

PS: Do not read or write keys defined in the secure URL environment (HTTP.


7. storage event: triggered when the storage area changes, it can be captured using window. onstorage. If the target document is not active, the storage event is not triggered. 4 ~ 6.

Attributes of the storage event object:

Key: indicates the changed key; oldValue: indicates the old value of the changed key; newValue: indicates the new value of the changed key; url: indicates the url where the changed key is located; storageArea: indicates the Storage object in which a change occurs. (Onstorage is only implemented in IE9 and Opera)

 StorageSet the user KeyShow user KeyDelete user Key<Script type = "text/javascript"> function storageHander (event) {var myDiv = document. getElementById ("myDiv"); myDiv. innerHTML = "Storage changed:
"+ Event. key +"Key changed
Old Value"+ Event. oldValue +"Changed to New Value"+ Event. newValue +"
URL changed:"+ Event. url +"";}Window. onstorage = storageHander (); var strDomain =" 127.0.0.1 "; var oStorage; try {oStorage = window. localStorage? Window. localStorage: window. globalStorage [strDomain];} catch (err) {alert (err. message? Err. message: err. toString ();} function setItem (key, value) {oStorage. setItem (key, value); alert ("DOM Storage:" + key + "=" + value);} function getItem (key) {var myDiv = document. getElementById ("myDiv"); myDiv. innerHTML = oStorage. getItem (key);} function removeItem (key) {oStorage. removeItem (key); alert ("key" + key + "deleted");} </script>

Running results in IE:



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.