function setCookie(name, value, expiredays) {
var date = new Date();
date.setDate(date.getDate() + expiredays);
document.cookie = name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + date.toGMTString());
}
setCookie('username', 'Darren', 30);
function getCookie(name) {
if (document.cookie.length > 0) {
var start = document.cookie.indexOf(name + "="); //通过String对象的indexOf()来检查这个cookie是否存在,不存在就为 -1
if (start != -1) {
start = start + name.length + 1; //最后这个+1其实就是表示"="号啦,这样就获取到了cookie值的开始位置
var end = document.cookie.indexOf(";", start);// indexOf()第二个参数表示指定的开始索引的位置
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(start, end)); //通过substring()得到了值。想了解unescape()得先知道escape()是做什么的,都是很重要的基础
}
}
return "";
}
也有Jquery.cookie.js可以用
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
var path = options.path ? '; path=' + options.path : '';
var domain = options.domain ? '; domain=' + options.domain : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'cnblogs.com'});//设置
var cc = $.cookie('the_cookie');//获取
$.cookie('the_cookie', null);//删除
Web Storage
interface Storage{
readonly attribute unsigned long length;
getter DOMString key(in unsigned long index);
getter any getItem(in DOMString key,in any data);
deleter void removeItem(in DOMString key);
void clear();
}
优缺点
window.sessionStorage.setItem('mykey', 'niqiu');
window.sessionStorage.nikey = 'stone';
alert(window.sessionStorage.getItem('mykey'));
alert(window.sessionStorage.nikey);
将一段Json存入localstorage:
var data = new Object();
data.name = "stoneniqiu";
data.age = "26";
var str = JSON.stringify(data);
localStorage.setItem(data.name, str); function getstone() {
var raw = localStorage.getItem("stoneniqiu");
var data = JSON.parse(raw);
alert(data.name + data.age);
}
getstone();
用LS存储用户的操作记录,个性化的代码片段。对于性能和使用范围可以看看这篇文章:让我们再谈谈浏览器资源加载优化
Web SQL
Web SQL Database 允许应用通过一个异步JavaScript接口访问SQLLite 数据库,但IE,Firefox并没有实现它,而且WHATWG也停止对Web Sql Database的开发。由于标准认定直接执行SQL语句不可取,Web Sql database 已经被索引数据库(Indexed Database)所取代。
浏览器 |
说明
|
IE
|
不支持
|
FireFox
|
不支持
|
Opera
|
10.5及以上支持
|
Chrome
|
3.0及以上支持
|
Safari
|
3.2及以上支持。 |
Database openDatabase(in DOMString name,in DOMString version,in DOMString displayName,in unsigned long estimatedSize,in optional DatabaseCallback creationCallback)
参数名称不言而喻 脚本用法:
var db=openDatabase("myDb","0.1","A list of to do items",20000)
这样就创建了一个数据库。
2.transaction:允许用户根据情况控制事务提交或回滚。完整定义:
transaction.executeSql(sqlquery,[],dataHandler,errorHandler):
sqlquery 为要执行的sql语句,[]这个数组表示sql语句中使用的参数数组。所有参数先用?号代替。然后依次将这些参数放在这个数组中。
脚本用法:
db.transaction(function(tx){})
实例:
transaction.executeSql("Update people set age-? where name=?;",[age,name]);
function dataHandler(transaction,errmsg){}
function errorHandler(transaction,errmsg){}
3.executeSql:用于执行真实的SQL查询。
实例:
function initdb() {
var name = ['C#', "C++", "C", "JavaScript", "Java", "PhP"];
db.transaction(function(tx) {
tx.executeSql('Create table if not exists mytable(id integer primary key autoincrement,name)');
for (var i = 0; i < name.length; i++) {
tx.executeSql('insert into mytable(name) values(?)', [name[i]]);
}
});
} initdb();
一张表包含了用 "AUTOINCREMENT" 修饰的列时, sqlite 将自动创建表 "SQLITE_SEQUENCE"。如果想清空记录,让编号归0,直接处理sqlite_sequence就可以了。
db.transaction(function(tx) {
tx.executeSql('create table if not exists t1(id unique,log)');
tx.executeSql('insert into t1(id,log) values(1,"created a db")');
tx.executeSql('insert into t1(id,log) values(1,"a good day")');
tx.executeSql('insert into t1(id,log) values(1,"hello")');
}); //读取:
db.transaction(function(tx) {
tx.executeSql('select * from t1', [], function(tx, results) {
var len = results.rows.length, i;
var msg = "<p>共有" + len + "条记录</p>";
document.getElementById("res").innerHTML = msg;
for (i = 0; i < len; i++) {
msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
document.querySelector('#res').innerHTML += msg;
}
},null);
});
IndexedDB
IndexedDB很像Nosql。能够存储可观的结构化数据,一个单独的数据库项目的大小没有限制。然而可能会限制每个 IndexedDB 数据库的大小。这个限制(以及用户界面对它进行断言的方式)在各个浏览器上也可能有所不同。比如Firefox4中一个站点超过50M,Firefox会向用户请求权限。在移动端是5M.
使用异步 API 方法调用完后会立即返回,而不会阻塞调用线程。
文档中的示例:
var request = indexedDB.open("library");
request.onupgradeneeded = function () {
// The database did not previously exist, so create object stores and indexes.
var db = request.result;
var store = db.createObjectStore("books", { keyPath: "isbn" });
var titleIndex = store.createIndex("by_title", "title", { unique: true });
var authorIndex = store.createIndex("by_author", "author"); // Populate with initial data.
store.put({ title: "Quarry Memories", author: "Fred", isbn: 123456 });
store.put({ title: "Water Buffaloes", author: "Fred", isbn: 234567 });
store.put({ title: "Bedrock Nights", author: "Barney", isbn: 345678 });
}; request.onsuccess = function () {
db = request.result;
};
更详细的操作我这里也不赘述了,功能比较强大,支持group,filter等大家可以去看下面两篇文章。
IndexedDatabase API http://www.w3.org/TR/IndexedDB/