

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/
