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

How H5 operates local storage and local database

php中世界最好的语言
Release: 2018-03-27 10:50:04
Original
3787 people have browsed it

This time I will show you how H5 operates local storage and local database, what are the precautions for H5 to operate local storage and local database, the following is a practical case, let’s come together take a look.

Local Storage

1.1 The background of the origin of local storage

Due to the size of cookies in the HTML4 era , format, storage data format and other restrictions. If a website application wants to store some of the user's information on the browser side, it can only use cookies. However, these limitations of cookies mean that cookies can only store simple data such as identifiers such as IDs.

The following are cookie limitations:

Most browsers support cookies up to 4096 bytes.

Browsers also limit the number of cookies that a site can store on a user's computer. Most browsers only allow 20 cookies per site; if you try to store more cookies, the oldest cookies are discarded.

Some browsers also place an absolute limit on the total number of cookies they will accept from all sites, usually 300.

Cookies will be sent to the backend server along with Http requests by default, but not all requests require cookies. For example, requests for js, css, pictures, etc. do not require cookies.

In order to break a series of limitations of Cookie, HTML5 can directly store large amounts of data to the client browser through the new API of JS, and supports complex local databases, making JS more efficient.

html5 supports two types of WebStorage:

Permanent local storage (localStorage)

Session-level local storage (sessionStorage)

1.2 Permanent local storage: localStorage

The localStorage object has been added to the latest JS API to facilitate users to store permanently stored web-side data. Moreover, the data will not be sent to the backend server along with the Http request, and the size of the stored data basically does not need to be considered, because the Html5 standard requires the browser to support at least 4MB. Therefore, this completely subverts the limitations of Cookie and provides a better solution for the Web. The application locally stores complex user trace data to provide very convenient technical support. Next, we will introduce the commonly used methods of localStorage.

localStorage provides four methods to assist us in performing related operations on local storage.

setItem(key,value) adds local storage data. The two parameters are very simple and I won’t go into details.

getItem(key) obtains the corresponding Value through key.

removeItem(key) deletes local data by key.

clear() clears data.

The code is as follows:

<script type="text/javascript">
    //添加key-value 数据到 sessionStorage
    localStorage.setItem("demokey", "http://www.shiyanlou.com");
    //通过key来获取value
    var dt = localStorage.getItem("demokey");
    alert(dt);
    //清空所有的key-value数据。
    //localStorage.clear();
    alert(localStorage.length);
</script>
Copy after login

1.3 Session-level local storage: sessionStorage

A Js object is added in HTML5: sessionStorage; through this object Session-level WebStorage stored in the browser can be manipulated directly. The data stored in sessionStorage is first in the form of Key-Value. In addition, it is related to the current session of the browser. When the session ends, the data will be automatically cleared, similar to a cookie with no expiration time set.

sessionStorage provides four methods to assist us in performing related operations on local storage.

setItem(key,value) adds local storage data. The two parameters are very simple and I won’t go into details.

getItem(key) obtains the corresponding Value through key.

removeItem(key) deletes local data by key.

clear() clears data.

The code is as follows:

<script type="text/javascript">
    //添加key-value 数据到 sessionStorage
    sessionStorage.setItem("demokey", "http://blog.itjeek.com");
    //通过key来获取value
    var dt = sessionStorage.getItem("demokey");
    alert(dt);
    //清空所有的key-value数据。
    //sessionStorage.clear();
    alert(sessionStorage.length);
</script>
Copy after login

1.4 Powerful local data

Although HTML5 already provides powerful localStorage and sessionStorage, both of them It can only provide data for storing simple data structures, but it can do nothing for data of complex web applications. What's amazing is that HTML5 provides a browser-side database support, allowing us to create a local database on the browser side directly through the JS API, and supports standard SQL CRUD operations, making offline web applications more convenient to store structures. ized data. Next, we will introduce the relevant APIs and usage of local data.

The most basic steps to operate a local database are:

The first step: openDatabase method: Create an object to access the database.

第二步:使用第一步创建的数据库访问对象来执行transaction方法,通过此方法可以设置一个开启事务成功的事件响应方法,在事件响应方法中可以执行SQL.

第三步:通过executeSql方法执行查询,当然查询可以是:CRUD。

接下来分别介绍一下相关的方法的参数和用法。

1.4.1 openDatabase方法

//Demo:获取或者创建一个数据库,如果数据库不存在那么创建之

var dataBase = openDatabase(“student”, “1.0”, “学生表”, 1024 * 1024, function () { });
Copy after login

openDatabase方法打开一个已经存在的数据库,如果数据库不存在,它还可以创建数据库。几个参数意义分别是:

数据库名称。

数据库的版本号,目前来说传个1.0就可以了,当然可以不填;

对数据库的描述。

设置分配的数据库的大小(单位是kb)。

回调函数(可省略)。

初次调用时创建数据库,以后就是建立连接了。

1.4.2 db.transaction方法

可以设置一个回调函数,此函数可以接受一个参数就是我们开启的事务的对象。然后通过此对象可以执行SQL脚本。

1.4.3 executeSql方法执行查询
 

ts.executeSql(sqlQuery,[value1,value2..],dataHandler,errorHandler)
Copy after login

参数说明:

qlQuery:需要具体执行的sql语句,可以是create、select、update、delete;

[value1,value2..]:sql语句中所有使用到的参数的数组,在executeSql方法中,将s>语句中所要使用的参数先用“?”代替,然后依次将这些参数组成数组放在第二个参数中;

dataHandler:执行成功时调用的回调函数,通过该函数可以获得查询结果集;

errorHandler:执行失败时调用的回调函数;

1.5 综合实例

<head>
 <script src="Scripts/jquery-1.5.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        function initDatabase() {
            var db = getCurrentDb();//初始化数据库
            if(!db) {alert("您的浏览器不支持HTML5本地数据库");return;}
            db.transaction(function (trans) {//启动一个事务,并设置回调函数
                //执行创建表的Sql脚本
                trans.executeSql("create table if not exists Demo(uName text null,title text null,words text null)", [], function (trans, result) {
                }, function (trans, message) {//消息的回调函数alert(message);});
            }, function (trans, result) {
            }, function (trans, message) {
            });
        }
        $(function () {//页面加载完成后绑定页面按钮的点击事件
            initDatabase();
            $("#btnSave").click(function () {
                var txtName = $("#txtName").val();
                var txtTitle = $("#txtTitle").val();
                var txtWords = $("#txtWords").val();
                var db = getCurrentDb();
                //执行sql脚本,插入数据
                db.transaction(function (trans) {
                    trans.executeSql("insert into Demo(uName,title,words) values(?,?,?) ", [txtName, txtTitle, txtWords], function (ts, data) {
                    }, function (ts, message) {
                        alert(message);
                    });
                });
                showAllTheData();
            });
        });
        function getCurrentDb() {
            //打开数据库,或者直接连接数据库参数:数据库名称,版本,概述,大小
            //如果数据库不存在那么创建之
            var db = openDatabase("myDb", "1.0", "it's to save demo data!", 1024 * 1024); ;
            return db;
        }
        //显示所有数据库中的数据到页面上去
        function showAllTheData() {
            $("#tblData").empty();
            var db = getCurrentDb();
            db.transaction(function (trans) {
                trans.executeSql("select * from Demo ", [], function (ts, data) {
                    if (data) {
                        for (var i = 0; i < data.rows.length; i++) {
                            appendDataToTable(data.rows.item(i));//获取某行数据的json对象
                        }
                    }
                }, function (ts, message) {alert(message);var tst = message;});
            });
        }
        function appendDataToTable(data) {//将数据展示到表格里面
            //uName,title,words
            var txtName = data.uName;
            var txtTitle = data.title;
            var words = data.words;
            var strHtml = "";
            strHtml += "<tr>";
            strHtml += "<td>"+txtName+"</td>";
            strHtml += "<td>" + txtTitle + "</td>";
            strHtml += "<td>" + words + "</td>";
            strHtml += "</tr>";
            $("#tblData").append(strHtml);
        }
    </script>
</head>
    <body>
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="txtName" id="txtName" required/></td>
            </tr>
               <tr>
                <td>标题:</td>
                <td><input type="text" name="txtTitle" id="txtTitle" required/></td>
            </tr>
            <tr>
                <td>留言:</td>
                <td><input type="text" name="txtWords" id="txtWords" required/></td>
            </tr>
        </table>
        <input type="button" value="保存" id="btnSave"/>
        <hr/>
        <input type="button" value="展示所哟数据" onclick="showAllTheData();"/>
        <table id="tblData">
        </table>
    </body>
</html>
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

H5怎么操作WebSQL数据库

Drag事件编辑器实现拖拽上传图片效果

The above is the detailed content of How H5 operates local storage 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!