HTML5 and Mobile Web: data storage

WebStorage

sessionStorage: The data stored in the session object. The so-called the session , refer to the user when browsing a Web site, closed elapsed from entering the site to the browser this time, the user is browsing the site takes time. Session object can be used during this time saved as claimed in any stored data.

localStorage: The data stored locally on the client's hardware devices, even if the browser is closed, the data still exists, we can still continue to use the next time you open a browser to access the site.

L the sessionStorage and localStorage difference

1. localStorage been stored in local data storage is permanent, unless the user deletes them or program; sessionStorage effective in the session period, the data is automatically deleted when the browser is closed;

2. localStorage is based on the domain can access any page within that domain, sessionStorage in saving its window, and the new window created by the current window in effect until the tab associated with closed

Cookie the distinction of sessionStorage and localStorage

1.cookie passed back and forth between the browser and the server, sessionStorage and localStorage not
greater 2.sessionStorage and localStorage of storage space, there are more rich-to-use interface, independent storage space

data storage

localStorage.setItem("key", "value);

 data collection

var val = localStorage.getItem("key");

Data deletion

var val = sessionStorage.removeItem(key);

Clear data

sessionStorage.clear();

Offline application (offline cache)

step:

1, write a manifest type of file that lists need to be cached to the local resource file browser.

2, the development of a Web page, the <html> element of "manifest" attribute will manifest file with the page binding.

3, to configure the server so that it can read the manifest file type.

manifest

Detailed: the manifest file is a simple text file in the file lists the file name does not need to be cached or cached resource file, resources and access paths to these files in a list. You can specify a page every single manifest file, you can specify a total of manifest file for the entire Web application.

In mobile applications, Web pages, when the browser to establish contact with the server, the browser will cache according to the list of files listed in the manifest, the corresponding resource file cached locally.

Function: which files need to be saved, which do not need to save the file, online and offline which files need to call

format:

CACHE MANIFEST It indicates the version number
CACHE When expressed offline browser to cache files locally to the list of server resources. When writing manifest file type for a page, the page does not need to put in the list because the browser automatically cached on this page during local resources cache.
NETWORK A list of resources expressed the need to access files when online, these files can be accessed only establish a link between the browser and the server. If set to "*", said that apart from the "CACHE:" not outside the local cache tag marked to cache files.
FALLBACK Expressed in pairs listed in the file does not access the files on the bench. Where the former is inaccessible files, which is a substitute file, that is, when "/Project/Index.jsp" inaccessible files, the browser tries to access the "/BkProject/Index.jsp" file.

note:

(1) In the manifest file, the first line must be "CACHE MANIFEST", indicates that this is a format file server resources locally cached by the browser.
(2) at the time of writing comments need to start a new line, and the "#" at the beginning.
Content (3) manifest file allows rewriting the classification mark that can write multiple "CACHE:" tag or mark the other two.
(4) If the tag classification is not found, it is considered "CACHE:" resource files and tags.
(5) recommendations indicate the version number of each type of file manifest by way of comment, for use in updating the file. For example, in the above demo code, "# version 0.0.0" represents the version number of default.

<html manifest="mr.manifest">
...
</html>

Web SQL

Open / create database

//openDatabase可以打开一个已经存在的数据库,如果不存在则创建
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
mydb:数据库名称
1.0:版本号
Test DB:描述文本
2*1024*1024:数据库大小,2MB

Create a table

function crateTable() {
	var sql = 'create table if not exists t_plan(title, content, target_time,create_time)';
	db.transaction(function(tx) {
	    tx.executeSql(sql, null, function(tx, rs) {
		    $("#msg").html('创建表成功');
	    }, errorCallback);
	});
}
================
sql:执行的SQL语句
null:参数,用于动态传参
fuction(tx,rs):成功函数
errorCallback:失败回滚

CRUD

function addPlan(values) {
	var sql = 'INSERT INTO t_plan (title, content, target_time, create_time) VALUES (?,?,?,?)';
	db.transaction(function(tx) {
		tx.executeSql(sql, values, function(tx, rs) {
			var effectRow = rs.rowsAffected;
			$("#msg").html('影响记录条数:' + effectRow);
		}, errorCallback);
	});
}
function deletePlan(values) {
	var sql = 'DELETE FROM t_plan WHERE title = ?';
	db.transaction(function(tx) {
		tx.executeSql(sql, values, function(tx, rs) {
			var effectRow = rs.rowsAffected;
			$("#msg").html('影响记录条数:' + effectRow);
		}, errorCallback);
	});
}
function updatePlan(values) {
	var sql = 'UPDATE t_plan SET content = ? WHERE title = ?';
	db.transaction(function(tx) {
		tx.executeSql(sql, values, function(tx, rs) {
			var effectRow = rs.rowsAffected;
			$("#msg").html('影响记录条数:' + effectRow);
		}, errorCallback);
	});
}
function getPlanList() {
	var sql = 'SELECT * FROM t_plan';
	db.transaction(function(tx) {
		tx.executeSql(sql, null, function(tx, rs) {
			$("#msg").html('list:' + rs.rows+"<br/>");
			$("#msg").html('item:' + JSON.stringify(rs.rows.item(0)));
			$("#msg").html('item:' + JSON.stringify(rs.rows.item(0)));
			$("#msg").html('item:' + rs.rows.item(0).title); 
		}, errorCallback);
	});
};
					

IndexDB

Open / create database

// 打开数据库,两个参数(数据库名字,版本号),如果数据库不存在则创建一个新的库
var request = window.indexedDB.open('myDatabase', '1');

indexedDB.open () method returns a IDBRequest object. The objects three events error, success, upgradeneeded, the result of the processing operation to open the database.

==============error============
request.onerror = function (event) {
  console.log('数据库打开报错');
};
==============success===========
var db;
request.onsuccess = function (event) {
  db = request.result;
  console.log('数据库打开成功');
};  //通过request对象的result属性拿到数据库对象
=============upgradeneeded======
var db;
request.onupgradeneeded = function (event) {
  db = event.target.result;
}

Create a table

request.onupgradeneeded = function(event) {
  db = event.target.result;
  var objectStore = db.createObjectStore('person', { keyPath: 'id' });
}

CRUD

var request = db.transaction(['person'], 'readwrite')
    .objectStore('person')
    .add({ id: 1, name: '张三', age: 24, email: '[email protected]' });
=================
var request = db.transaction(['person'], 'readwrite')
    .objectStore('person')
    .delete(1);
=================
var request = db.transaction(['person'], 'readwrite')
    .objectStore('person')
    .put({ id: 1, name: '李四', age: 35, email: '[email protected]' });
================
var transaction = db.transaction(['person']);
var objectStore = transaction.objectStore('person');
var request = objectStore.get(1);
 request.onsuccess = function( event) {
      if (request.result) {
        console.log('Name: ' + request.result.name);
      }
}
=======遍历========
var objectStore = db.transaction('person').objectStore('person');
objectStore.openCursor().onsuccess = function (event) {
     var cursor = event.target.result;
     if (cursor) {
         console.log('Name: ' + cursor.value.name);
     }
}

 

 

 

 

 

 

 

 

 

 

Published 349 original articles · won praise 161 · views 190 000 +

Guess you like

Origin blog.csdn.net/qq_42192693/article/details/103342962