This time I will bring you a detailed introduction to H5's local storage and local database. What are the precautions when using H5's local storage and local database? The following is a practical case. Let’s take a look.
Local Storage
1.1 The background of the origin of local storage
Due to limitations in the size, format, and storage data format of cookies in the HTML4 era, if a website application wants to store it on the browser side, Some of the user's information can only be obtained with the help of 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 Permanence 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>
1.3 Session-level local storage: sessionStorage
A Js object has been added in HTML5: sessionStorage; through this object, you can directly operate the storage in the browser Session-level WebStorage in the server. 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>
1.4 Powerful local data
Although HTML5 has provided powerful localStorage and sessionStorage, both of them can only store simple data. Structured data is powerless for complex web application data. 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.
Step 2: Use the database access object created in the first step to execute the transaction method. Through this method, you can set an event response method to start the transaction successfully. In the event response method, you can execute SQL.
Step 3: Execute the query through the executeSql method. Of course, the query can be: CRUD.
Next, we will introduce the parameters and usage of the relevant methods.
1.4.1 openDatabase method
//Demo: Get or create a database. If the database does not exist, create it
var dataBase = openDatabase(“student”, “1.0”, “学生表”, 1024 * 1024, function () { });
The openDatabase method opens an existing database. If the database does not exist, it can also create a database. The meanings of several parameters are:
Database name.
The version number of the database. Currently, 1.0 is enough. Of course, you don’t need to fill it in;
Description of the database.
Set the size of the allocated database (unit is kb).
Callback function (can be omitted).
Create the database when calling for the first time, and then establish the connection.
1.4.2 db.transaction方法
可以设置一个回调函数,此函数可以接受一个参数就是我们开启的事务的对象。然后通过此对象可以执行SQL脚本。
<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>
相信看了这些案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
相关阅读:
The above is the detailed content of Detailed introduction to H5's local storage and local database. For more information, please follow other related articles on the PHP Chinese website!