Home > Web Front-end > H5 Tutorial > body text

Web Storage Overview and Local Database

PHP中文网
Release: 2017-06-21 15:24:03
Original
1366 people have browsed it

Previous article: HTML5 Notes 2 - Detailed explanation of HTML5 audio/video tags

Web Storage Overview

In HTML5, in addition to the Canvas element, another new addition is very important The function is the Web Storage function that can save data locally on the client. Previously, Cookies could be used to save simple user information such as user names on the client. However, through long-term use, people have discovered that using Cookies to store permanent data exists. Some Problems.

    Size: The size of Cookies is limited to 4KB
  • Bandwidth: Cookies are sent together with HTTP errors, so part of the sending will be wasted The bandwidth used by cookies
  • Complexity: It is difficult to manipulate cookies correctly.
  • In response to the above problems, HTML5 has re-provided the function of saving data locally on the client, which is Web Storage.

Web Storage function.

As the name suggests, the Web Storage function is the function of storing data on the Web. The storage here is for the client's local area. Specifically divided into two types:

sessionStorage:

Save data in the session object. Session refers to the time that elapses from entering the website to closing the browser when a user is browsing a website, that is, the time it takes for the user to browse the website. The session object can be used to save any data that needs to be saved during this period.

localStorage:

Save the data in the local hardware device (hard disk) of the client. Even if the browser is closed, the data still exists and will still exist the next time you open the browser to visit the website. You can

continue using it. localstorage is stored through key-value pairs. Development tools I use HBuilder.exe

to create a new Test.html page, the code is as follows:

##

<html><head><title></title><meta charset="UTF-8" /><script type="text/javascript">function saveSessiontorage(id) {var targat = document.getElementById(id);var str = targat.value;
                sessionStorage.setItem("msg", str);
            }function getSessionStorage(id) {var targat = document.getElementById(id);var msg = sessionStorage.getItem("msg");
                targat.innerHTML = msg;
            }function saveLocalStorage(id) {var targat = document.getElementById(id);var str = targat.value;
                localStorage.setItem("msg", str);
            }function getLocalStorage(id) {var targat = document.getElementById(id);var msg = localStorage.getItem("msg");
                targat.innerHTML = msg;
            }</script></head><body><p id="msg"></p><input type="text" id="txt" /><input type="button" value="存储数据" onclick="saveSessiontorage(&#39;txt&#39;)" /><input type="button" value="读取数据" onclick="getSessionStorage(&#39;msg&#39;)" /><p id="msg1"></p><p>    <input type="text" id="txt1" /></p><input type="button" value="Local存储数据" onclick="saveLocalStorage(&#39;txt1&#39;)" /><input type="button" value="Local读取数据" onclick="getLocalStorage(&#39;msg1&#39;)" /></body></html>
Copy after login
View Code
localStorage

Close the browser and then open it again, the read data still exists, and sessionStorage

Close browsing After opening the device to read the data, it disappeared.

Use as a simple database Use Web Storage as a simple database. If you can solve data retrieval and manage columns, you can use Web Storage as a database.

Create a new Register.html page with the following code:

##
<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><script type="application/javascript">function addUser () {var data=new Object;
                data.name=document.getElementById("txtName").value;
                data.phone=document.getElementById("txtPhone").value;
                data.address=document.getElementById("txtAddress").value;var str=JSON.stringify(data);
                localStorage.setItem(data.name,str);
                alert("注册成功");
            }function search (txt) {var filed=document.getElementById(txt).value;var str=localStorage.getItem(filed);var data=JSON.parse(str);var result="用户名:"+data.name+"</br>"+"电话:"+data.phone+"</br>"+"地址:"+data.address
                document.getElementById("txtMsg").innerHTML=result;
            }</script></head><body><div>用户名:<input type="text" id="txtName" /></div><div>电话号码:<input type="text" id="txtPhone" /></div><div>地址:<input type="text" id="txtAddress" /></div><div><input type="button" value="注册" onclick="addUser()"></div><br /><div>用户名:<input type="text" id="txtSearch"><input type="button" value="Search" onclick="search(&#39;txtSearch&#39;)"/></div><div id="txtMsg"></div></body></html>
Copy after login

View Code
HTML5 local database
In HTML5, the content that can be stored locally on the client has been greatly enriched, and many functions have been added to convert data that originally had to be stored on the server to be stored on the client. The client is local, thus greatly improving the performance of Web applications and reducing the burden on the server. Using the Web era has returned to the era of "client-side emphasis and server-side emphasis". There are two local databases built into HTML5, one is SQLLite and the other is indexedDB.

Use executeSql to execute the query

1.transaction.executeSql(sqlquery,[],dataHandler,errorHandler);

2.function dataHandler(transaction,results);

3.function errorHandler(transaction,errmsg);

4.rows.length gets the number of recordsCreate a new SqlTest.html with the following code:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title></head><body><script type="application/javascript">var db=openDatabase("mydb","1.0","test db",1024*100); //参数分别为:(数据库名称,版本号,描述,大小) 如果数据库不存在则创建//            db.transaction(function(tx) {//                tx.executeSql("")//            })            transaction.executeSql("CREATE TABLE IF NOT EXISTS MsgData(name TEXT,msg,TEXT,createtime INTERGER)",[],function(){},function(){});//参数:(sql语句,sql参数数组,执行成功的回调函数,执行失败的回调函数)</script></body></html>
Copy after login


HTML5 indexedDB database

In HTML5, a new database called "indexedDB" is added, which is a NoSQL database stored locally on the client. database.

Create a new IndexedDBTest.html with the following code:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><script type="application/javascript">//统一IndexedDB在不同浏览器的实现            window.indexedDB = window.indexedDB ||window.mozIndexedDB ||window.webkitIndexedDB ||window.msIndexedDB;
            window.IDBTransaction = window.IDBTransaction ||window.webkitIDBTransaction ||window.msIDBTransaction;
            window.IDBKeyRange = window.IDBKeyRange ||window.webkitIDBKeyRange ||window.msIDBKeyRange;                function connDB () {var dbName="indexedDBTest";var dbVersion=1;var idb;var dbConnect=indexedDB.open(dbName,dbVersion);
                    dbConnect.onsuccess=function (e) {
                        idb=e.target.result;
                        alert("数据库连接成功!")
                    }
                    dbConnect.onerror=function(e){
                        alert("数据库连接失败!");
                    }
                }</script></head><body><input type="button" value="连接数据库"  onclick="connDB()"/></body></html>
Copy after login

View Code

数据库的版本更新

只是成功链接数据库,我们还不能执行任何数据操作,我们还应该创建相当于关系型数据库中数据表的对象仓库与用于检索数据的索引。

新建versionUpdate.html,代码如下:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><script type="application/javascript">//统一IndexedDB在不同浏览器的实现            window.indexedDB = window.indexedDB ||window.mozIndexedDB ||window.webkitIndexedDB ||window.msIndexedDB;
            window.IDBTransaction = window.IDBTransaction ||window.webkitIDBTransaction ||window.msIDBTransaction;
            window.IDBKeyRange = window.IDBKeyRange ||window.webkitIDBKeyRange ||window.msIDBKeyRange;                function VersionUpdate () {var dbName="indexedDBTest";var dbVersion=2;var idb;var dbConnect=indexedDB.open(dbName,dbVersion);
                    dbConnect.onsuccess=function (e) {
                        idb=e.target.result;
                        alert("数据库连接成功!")
                    }
                    dbConnect.onerror=function(e){
                        alert("数据库连接失败!");
                    }
                    dbConnect.onupgradeneeded=function(e){
                        idb=e.target.result;var ts=e.target.transaction;var oldVersion=e.oldVersion;var newVersion=e.newVersion;
                        alert("数据库更新成功!旧版本号:"+oldVersion+"------新版本号:"+newVersion);
                    }
                }</script></head><body><input type="button" value="更新数据库" onclick="VersionUpdate()" /></body></html>
Copy after login
View Code

创建对象仓库

对于创建对象仓库与索引的操作,我们只能在版本更新事务内部进行,因为在indexedDB API中不允许数据库中的对象仓库在同一个版本中发生改变。

新建createStorge.html,代码如下:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><script type="application/javascript">//统一IndexedDB在不同浏览器的实现            window.indexedDB = window.indexedDB ||window.mozIndexedDB ||window.webkitIndexedDB ||window.msIndexedDB;
            window.IDBTransaction = window.IDBTransaction ||window.webkitIDBTransaction ||window.msIDBTransaction;
            window.IDBKeyRange = window.IDBKeyRange ||window.webkitIDBKeyRange ||window.msIDBKeyRange;                function CreateStorge () {var dbName="indexedDBTest";var dbVersion=2;var idb;var dbConnect=indexedDB.open(dbName,dbVersion);
                    dbConnect.onsuccess=function (e) {
                        idb=e.target.result;
                        alert("数据库连接成功!")
                    }
                    dbConnect.onerror=function(e){
                        alert("数据库连接失败!");
                    }
                    dbConnect.onupgradeneeded=function(e){
                        idb=e.target.result;var name="user";var optionParams={keyPath:"userid",autoIncrement:false};var store=idb.createObjectStore(name,optionParams);
                        alert("对象仓库创建成功!");
                    }
                }</script></head><body><input type="button" value="创建对象仓库" onclick="CreateStorge()" /></body></html>
Copy after login
View Code

 

The above is the detailed content of Web Storage Overview and Local Database. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source: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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!