HTML5's local storage function

HTML5's local storage function

The local storage introduced in this article are: Web Storage, Web SQL database, IndexedDB.

Web Storage

Web Storage is a very important function introduced by HTML5. It can store data locally on the client side. It is similar to HTML4 cookies, but the achievable functions are much stronger than cookies. The size of cookies is limited to 4KB. The official recommendation of Web Storage is for each Website 5MB.

Web Storage is divided into two types:

sessionStorage saves the data in the session and disappears after the browser is closed;

localStorage always saves data locally on the client; html5 localStorage is one of the APIs of HTML5 local storage web storage feature, html5 localStorage is used to store some temporary offline data, and save the data in the client, just like file and database , Storage has a permanent nature.

[Where is the localstorage folder? See appendix]

 

Regardless of whether it is sessionStorage or localStorage, the available APIs are the same. The following are commonly used (take localStorage as an example):

Save data: localStorage.setItem(key,value);

Read data: localStorage.getItem(key);

Delete a single data: localStorage.removeItem(key);

Delete all data: localStorage.clear();

Get the key of an index: localStorage.key(index);

Among them, both key and value must be strings. In other words, the web Storage API can only manipulate strings.

For security reasons, when money or other important information is involved, it is better to have a background.

【Note

LocalStorage storage method, the following three methods have the same effect:

localStorage.name = 'vanida ;

localStorage["name"]='vanida';

localStorage.setItem("name","vanida");

 

LocalStorage obtains the value method, the following three methods have the same effect:

var name = localStorage["name"]

var name= localStorage.name

var name= localStorage.getItem("name");

 

LocalStorage clears a specific value method, the following two methods have the same effect:

localStorage.removeItem("name");

localStorage.name='';

 

LocalStorage clear all values ​​method:

localStorage.clear()

 

Code to detect whether the browser stores localstorage locally:

if(window.localStorage){

 alert('This browser supports local storage');

}else{

 alert('TThis browser does not support local storage');

}

 

Below, a simple example is given: a simple address book applet, to achieve the following functions:

Enter contacts. Each contact record has two fields: name and mobile phone number, which are stored in localStorage with mobile phone number as the key;

According to the mobile phone number, find the owner or delete it;

List all currently saved contact information;

code show as below:

<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8"> 
<title>HTML5本地存储之WebStorage例子</title>
<script>
//调用函数
//loadAll();
//保存数据  
function save(){  
    var user_name = document.getElementById("user_name").value;  
    var mobilephone = document.getElementById("mobilephone").value;  
    localStorage.setItem(mobilephone,user_name);  
    loadAll();  
}  
//将所有存储在localStorage中的对象提取出来,并展现到界面上  
function loadAll(){  
    var list = document.getElementById("list");  
    if(localStorage.length>0){  
        var result = "<table border='1'>";  
        result += "<tr><td>姓名</td><td>手机号码</td></tr>";  
        for(var i=0;i<localStorage.length;i++){  
            var mobilephone = localStorage.key(i);  
            var name = localStorage.getItem(mobilephone);  
            result += "<tr><td>"+name+"</td><td>"+mobilephone+"</td></tr>";  
        }  
        result += "</table>";  
        list.innerHTML = result;  
    }else{  
        list.innerHTML = "目前数据为空,赶紧开始加入联系人吧";  
    }  
}  
//查找数据  
function find(){  
    var search_phone = document.getElementById("search_phone").value;  
    var name = localStorage.getItem(search_phone);  
    var find_result = document.getElementById("find_result");  
    find_result.innerHTML = search_phone + "的机主是:" + name;  
}
//删除数据  
function del(){
     //window.localStorage.clear();  //删除全部数据
     var search_phone = document.getElementById("search_phone").value;
     localStorage.removeItem(search_phone);// 查找键值对删除
     loadAll();  
}
</script>
</head>
<body onload="loadAll()">
<h3><center>简单的通讯录<center></h3>
<hr color="#666666">
<div style="border: 2px dashed #ccc;width:320px;text-align:center;">     
<label for="user_name">姓名:</label>  
<input type="text" id="user_name" name="user_name" class="text"/>  
 <br/>  
<label for="mobilephone">手机:</label>  
<input type="text" id="mobilephone" name="mobilephone"/>  
<br/>  
<input type="button" onclick="save()" value="新增记录"/>  
<hr/>  
<label for="search_phone">输入手机号:</label>  
<input type="text" id="search_phone" name="search_phone"/>  
<input type="button" onclick="find()" value="查找机主"/> 
<input type="button" onclick="del()" value="删除记录"/>   
<p id="find_result"><br/></p>  
</div>  
<br/>  
<div id="list">  
</div>  
<br/>  
<dividdivid="list">  
</div>  
</body>
</html>

Save the file as WebStorageA.html and place it in the folder (directory) (I am D:\webpage exercises, you can decide according to your actual situation), open iframeDemo.html with a browser, the display effect is as follows:

Two new contact records have been added.

 

Web SQL database

The Web SQL database API is not part of the HTML5 specification, but it is an independent specification that introduces a set of APIs for operating the client database using SQL. Use query statements similar to mysql queries to operate the local database.

Determine whether the browser supports this feature

if (window.openDatabase) {

    alert('The current browser supports webSQL!');      

} else {

     alert('The current browser does not support webSQL!!!');

}

 

Core method:

①openDatabase: This method uses an existing database or a newly created database to create a database object.

// The five parameters corresponding to the openDatabase() method are: database name, version number, description text, database size, and creation callback, such as:

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024,fn);

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:

1. The database name.

2. The version number of the database. At present, it is enough to pass 1.0, of course, it is not necessary to fill in;

3. A description of the database.

4. Set the size of the allocated database (unit is kb).

5. Callback function (can be omitted). The database is created when it is called for the first time, and then the connection is established.

 

②transaction: This method allows us to control a transaction, and perform commit or rollback based on this situation.

// start transaction

database.transaction(function (sql) {

     // Operate the addition and deletion of the database here to check

});   

The transaction method can set a callback function, this function can accept a parameter that is the object of the transaction we opened. Then the Sql script can be executed through this object, which can be combined with the following steps.

③executeSql: This method is used to execute the actual SQL query.

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

Parameter Description:

qlQuery: The sql statement that needs to be executed specifically, which can be create, select, update, delete;

value1,value2..]: An array of all the parameters used in the sql statement. In the executeSql method, replace the parameters to be used in the s> statement with "?", and then put these parameters into an array in the second Parameters

ataHandler: The callback function is called when the execution is successful, and the query result set can be obtained through this function;

errorHandler: the callback function called when the execution fails;

 

Here is a demo (running on the browser console), the code is as follows:

// 打开|创建DB
var db = openDatabase('corp', '1.0', 'corporation info', 2 * 1024);

// 创建数据表
db.transaction(function (tx) {
	tx.executeSql('create table if not exists corporation (id unique, name)');
});

// 新增数据行
db.transaction(function (tx) {
	tx.executeSql('insert into corporation (id, name) values (1, "Baidu")');
	tx.executeSql('insert into corporation (id, name) values (?, ?)', [2, 'Alibaba']);
	tx.executeSql('insert into corporation (id, name) values (3, "Tencent")');
});

// 查询
db.transaction(function(tx) {
	/*tx.executeSql(SQL语句, SQL参数列表, func, null);*/
	tx.executeSql('select * from corporation', [], function(tx, results) {
		var len = results.rows.length;
		console.log('记录条数:', len);
		for (var i = 0; i < len; i++) {
			var record = results.rows.item(i);
			console.log(record.id, record.name);
		}
	}, null);
});

// 删除
db.transaction(function(tx) {
	/*tx.executeSql('delete from corporation where id = ?', [id]);*/
	tx.executeSql('delete from corporation where id = 1');
});

// 更新
db.transaction(function(tx) {
	tx.executeSql('update corporation set name = ? where id = ?', ['Ali', 2])
});

 

Open the browser (edge ​​browser is used here), press F12 to run in the console (console), see the figure below:

IndexedDB

IndexedDB (IndexedDB), respected by W3C, as a part of HTML5, is very useful for creating data-intensive offline HTML5 Web applications with rich local storage data. It also helps to cache data locally, enabling traditional online web applications (such as mobile web applications) to run and respond faster.

indexedDB is a lightweight NOSQL database that comes with the browser. Compared with Web Sql, it is more efficient, including indexing, transaction processing and query functions. In HTML5 local storage, IndexedDB stores the most data.

 

The overall structure of IndexedDB:

Among them, DB is a database, Object Store is a data table, and tem is equal to a record in the table.

Use IndexedDB see https://developer.mozilla.org/zh-CN/docs/Web/API/IndexedDB_API/Using_IndexedDB

An indexedDB database sample code is given below

<!DOCTYPE html>
<html>	
<head>		
<script>	
window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || 
window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || 
window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange|| window.webkitIDBKeyRange || 
window.msIDBKeyRange;
window.IDBCursor = window.IDBCursor || window.webkitIDBCursor || window.msIDBCursor;
const dbName = 'indexedDBTest'; //数据库名
const dbVersion = 20180408; //版本号
let idb; 
function window_onload(){
    document.getElementById("btnSaveData").disabled=true;
    document.getElementById("btnSearchData").disabled=true;
}
function ConnectDataBase(){
    /*连接数据库,dbConnect对象为一个IDBOpenDBRequest对象,代表数据库连接
    的请求对象*/
    let dbConnect = indexedDB.open(dbName, dbVersion);
    dbConnect.onsuccess = function(e){//连接成功   
        idb = e.target.result; //引用IDBDatabase对象 
        alert('数据库连接成功');
        document.getElementById("btnSaveData").disabled=false;
    };
    dbConnect.onerror = function(){
        alert('数据库连接失败');
    };
    dbConnect.onupgradeneeded = function(e){
        //数据库版本更新
        //e.target.result为一个IDBDatabase对象,代表连接成功的数据库对象
        idb = e.target.result; 
        /*e.target.transaction属性值为一个IDBTransaction事务对象,此处代表
        版本更新事务*/
        let tx = e.target.transaction;
        let name = 'Users2';
        let optionalParameters = {
            keyPath: 'userId',
            autoIncrement: false
        };
        let store = idb.createObjectStore(name,  optionalParameters);
        alert('对象仓库创建成功');
        name =  'userNameIndex';
        keyPath = 'userName';
        optionalParameters = {
            unique: false,
            multiEntry: false 
        };
 
        let idx = store.createIndex(name, keyPath, optionalParameters);
        alert('索引创建成功');
    };

}
function SaveData(){
    //开启事务
    let tx = idb.transaction(['Users2'],'readwrite'); 
    tx.oncomplete = function(){
        alert('保存数据成功');
        document.getElementById("btnSearchData").disabled=false;
    }
    tx.onabort = function(){alert('保存数据失败'); }
    let store = tx.objectStore('Users2');
    let value = {
        userId: 1,
        userName: '用户D',
        address: '住址1'
    };
    store.put(value);
    value = {
        userId:3,
        userName: '用户C',
        address: '住址2'
    };
    store.put(value);
    value = {
        userId: 5,
        userName: '用户B',
        address: '住址3'
    };
    store.put(value);
    value = {
        userId: 7,
        userName: '用户A',
        address: '住址4'
    };
    store.put(value);
}		
function SearchData(){
    //开启事务
    let range = IDBKeyRange.lowerBound('用户A');
    let tx = idb.transaction(['Users2'],'readonly'); 
    let store = tx.objectStore('Users2');
    let req = store.getKey(IDBKeyRange.bound(2,10));
    req.onsuccess = function(){
        alert('检索到一条数据,数据主键值为'+this.result);  
    }
    req.onerror = function(){
        alert('检索数据失败');
    }
} 
</script>		
</head>	
<body onload="window_onload()">
<input id="btnConnectDataBase" type="button" value="连接数据库" 
onclick="ConnectDataBase();"/>
<input id="btnSaveData"  type="button" value="保存数据" onclick="SaveData();"/>
<input id="btnSearchData" type="button" value="检索数据" onclick="SearchData();"/>
</body>
</html>

Open the browser (edge ​​browser is used here), press F12 to run in the console (console), see the figure below:

 

 

Appendix , where is the localstorage folder?

For Google Chrome, start the Chrome browser and enter Chrome:Version in the address bar of the Chrome browser

For the Microsoft edge browser, start the edge browser and enter edge:Version in the address bar of the Chrome browser

 

If you want to view it in the browser, open the debugging tool (F12), and you can view it under the application tab.

 

Guess you like

Origin blog.csdn.net/cnds123/article/details/113859797