search
HomeWeb Front-endH5 TutorialDetailed explanation of html5 local storage storage instance

HTML5storage Provides a way for websites to store information locally on your computer and retrieve it when needed later. This concept is similar to cookie, the difference is that it is designed for larger capacity storage. Cookie is limited in size, and cookie will be sent every time you request a new page. The #storage of HTML5 is stored on your computer. After the page is loaded, the website can use Javascript to get this data.

1sessionStorage

Detection

!!window.sessionStorage;

##Common methods

.key = value
.setItem(key,value)
.getItem(key)
.removeItem(key)
.clear()
rrree

Event:

##window.onstorage

Detect value changes, browser support is not good.

Note:

    The storage of cookies is limited to 4k. In comparison, Session storage has larger storage space, but as for the specific size, it depends on the specific implementation of the browser manufacturer.
  1. Cookie has a mechanism, which is to send the cookie to the server every time the client requests the server. This will undoubtedly do a lot of unnecessary operations, because not every request The server needs all the information of the cookie, and session storage solves this problem very well. It does not send it automatically, which reduces unnecessary work.
  2. The life cycle of data stored through sessionStorage is similar to Session. The data will no longer exist after closing the browser (or tab). But sessionStorage still exists after refreshing the page or using the "forward" or "back button".
  3. session storage The value of each window is independent (each window has its own data). Its data will disappear as the window is closed. The sessionStorage between windows It cannot be shared either.
  4. The key and value in setItem are stored in the form of strings. That is to say, if there is the following code: setItem(‘count’, 1); what you get through getItem(‘count’) + 5 will not be the expected 6 (integer), but ‘16’ (string).
  5. When you use setItem again to set the value of an existing key, the new value will replace the old value.
  6. When the data in storage changes, the corresponding event (window.onstorage) will be triggered. However, the current support for this event in various browsers is not perfect and can be ignored for the time being.

2localStorage

Detection

!!window.localStorage;

method and

sessionStorage Same

Explanation:

    Local storage only stores data in For client use, it will not be sent to the server (unless you intentionally do so).
  1. And for a certain domain, local storage is shared (multiple windows share a "database").
  2. localStorage用于持久化的本地存储,除非主动删除数据,否则数据是永远不会过期的。

举例

//结合JSON.stringify使用更强大    
var person = {'name': 'rainman', 'age': 24};    
localStorage.setItem("me", JSON.stringify(person));    
JSON.parse(localStorage.getItem('me')).name;    // 'rainman'    
    
/**  
* JSON.stringify,将JSON数据转化为字符串  
* JSON.stringify({'name': 'fred', 'age': 24});   // '{"name":"fred","age":24}'  
* JSON.stringify(['a', 'b', 'c']);               // '["a","b","c"]'  
* JSON.parse,反解JSON.stringify  
* JSON.parse('["a","b","c"]')                    // ["a","b","c"]  
*/

3Database Storage

对简单的数据存储,使用sessionStoragelocalStorage能够很好地完成,但是在对琐碎的关系数据进行处理之外,它就力所不及了。而这正是 HTML 5 Web SQL Database”API 接口的应用所在。

A、打开链接

var db = openDatabase("ToDo", "0.1", "A lalert of to do items.", 200000);    // 打开链接  
if(!db) { alert("Failed to connect to database."); }        // 检测连接是否创建成功

以上代码创建了一个数据库对象 db,名称是 Todo,版本编号为0.1db 还带有描述信息和大概的大小值。如果需要,这个大小是可以改变的,所以没有必要预先假设允许用户使用多少空间。

绝不可以假设该连接已经成功建立,即使过去对于某个用户它是成功的。为什么一个连接会失败,存在多个原因。也许用户代理出于安全原因拒绝你的访问,也许设备存储有限。面对活跃而快速进化的潜在用户代理,对用户的机器、软件及其能力作出假设是非常不明智的行为。比如,当用户使用手持设备时,他们可自由处置的数据可能只有几兆字节。

B、执行查询

db.transaction( function(tx) {   
    tx.executeSql(  
     "INSERT INTO ToDo (label, timestamp) values(?, ?)",   
     ['lebel', new Date().getTime()],   
      function(tx2, result){ alert('成功'); },   
          function(tx2, error){ alert('失败:' + error.message); }  
    );   
});
  1. 执行SQL语句使用database.transaction()函数,该函数只有一个参数,负责执行查询的函数。

  2. 该函数具有一个类型事务的参数(tx)。

  3. 该事务参数(tx)具有一个函数:executeSql()。这个函数使用四个参数:
    表示查询的SQL字符串;插入到查询中问号所在处的字符串数据;一个成功时执行的函数;一个失败时执行的函数。

  4. 执行成功的函数有两个参数:tx2,事务性参数;result,执行的返回结果,结构如图

  5. 执行成功的函数也有两个参数:tx2,事务性参数;error,错误对象,结构如图 

C、其它

  • Chrome支持; firefox(测试时版本4.01)不支持;IE8不支持。

D、示例

  //创建数据库    
  var db = openDatabase("users", "1.0", "用户表", 1024 * 1024);     
  if(!db){    
      alert("Failed to connect to database.");     
  } else {    
      alert("connect to database 'K'.");     
  }    
      
  // 创建表    
 db.transaction( function(tx) {     
     tx.executeSql(    
         "CREATE TABLE IF NOT EXISTS users (id REAL UNIQUE, name TEXT)",     
         [],     
         function(){ alert('创建users表成功'); },     
         function(tx, error){ alert('创建users表失败:' + error.message); }    
     );    
 });     
     
 // 插入数据    
 db.transaction(function(tx) {     
     tx.executeSql(    
         "INSERT INTO users (id, name) values(?, ?)",     
         [Math.random(), 'space'],     
         function(){ alert('插入数据成功'); },     
         function(tx, error){ alert('插入数据失败: ' + error.message);}    
     );     
 });     
     
 // 查询    
 db.transaction( function(tx) {     
     tx.executeSql(    
         "SELECT * FROM users", [],      
          function(tx, result) {    
             var rows = result.rows, length = rows.length, i=0;    
             for(i; i < length; i++) {     
                 alert(    
                     &#39;id=&#39; + rows.item(i)[&#39;id&#39;] +     
                     &#39;name=&#39;+ rows.item(i)[&#39;name&#39;]    
                 );     
             }     
         },     
         function(tx, error){    
             alert(&#39;Select Failed: &#39; + error.message);    
         }    
     );     
 });     
     
 // 删除表    
 db.transaction(function (tx) {      
     tx.executeSql(&#39;DROP TABLE users&#39;);     
 });

4globalStorage

这个也是html5中提出来,在浏览器关闭以后,使用globalStorage存储的信息仍能够保留下来,localStorage一样,域中任何一个页面存储的信息都能被所有的页面共享

基本语法

  • globalStorage['developer.mozilla.org'] —— 在developer.mozilla.org下面所有的子域都可以通过这个命名空间存储对象来进行读和写。

  • globalStorage['mozilla.org'] - All web pages under the mozilla.org domain name can be read and written through this namespace storage object.

  • globalStorage['org'] - All web pages under the .org domain name can be read and written through this namespace storage object.

  • globalStorage[''] - Any web page under any domain name can read and write through this namespace storage object

Method attribute

  • setItem(key, value) - Set or reset the key value.

  • getItem(key) - Get the key value.

  • removeItem(key) - Delete the key value.

  • Set key value: window.globalStorage["planabc.net"].key = value;

  • Get key value: value = window .globalStorage["planabc.net"].key;

Other

  • Expired The time is the same as localStorage, and some other features are also similar to localStorage.

  • Currently Firefox only supports globalStorage storage under the current domain. If you use the public domain, it will cause an error similar to "Security error" code: "1000".

5、Compatibility

##OperaSafari (WebKit)localStoragesessionStorage--2------

Method

##Chrome

##Firefox (Gecko)

Internet Explorer

4

2

8

##10.50

4

5

2

8

##10.50

4

##globalStorage

The above is the detailed content of Detailed explanation of html5 local storage storage instance. 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
Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.