JavaScript+IndexedDB实现留言板:客户端存储数据

之前看到贴友有问:用js怎么实现留言板效果。当时也写了一个,但是没有实现数据存储:http://www.ido321.com/591.html

现在将之前的改写一下,原来的HTML布局不变,为了防止Google调整字体,在原来的css中加入一个样式

   1: body{
   2:     font-size: 20px;
   3:     -webkit-text-size-adjust:none;
   4: }

在google中调整字体,可以见此文:http://www.ido321.com/652.html     有评论说不行,但是LZ在这个实例中测试了,是可以的

重点是js,完整的js代码修改如下:

   1:
   2:     var db;
   3:     var arrayKey=[]
   4:     var openRequest;
   5:     var lastCursor;
   6:
   7:     var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
   8:
   9:     function init()
  10:     {
  11:         //打开数据库
  12:         openRequest = indexedDB.open("messageIndexDB");
  13:         //只能在onupgradeneeded创建对象存储空间
  14:         openRequest.onupgradeneeded = function(e)
  15:         {
  16:             console.log("running onupgradeneeded");
  17:             var thisDb = e.target.result;
  18:             if(!thisDb.objectStoreNames.contains("messageIndexDB"))
  19:             {
  20:                 console.log("I need to create the objectstore");
  21:                 /*
  22:                  *创建对象存储空间,第一个参数必须和打开数据库的第一个参数一致
  23:                  *设置键名是id,并且可以自增.
  24:                  *autoIncrement默认是false,keyPath默认null
  25:                  */
  26:                 var objectStore = thisDb.createObjectStore("messageIndexDB", { keyPath: "id", autoIncrement:true });
  27:                 /*
  28:                  *创建索引
  29:                  *第一个参数是索引名,第二个是属性名,第三个设置索引特性
  30:                  */
  31:                 objectStore.createIndex("name", "name", { unique: false });
  32:             }
  33:         }
  34:
  35:         openRequest.onsuccess = function(e)
  36:         {
  37:             //e.target.result返回一个数据库实例
  38:             db = e.target.result;
  39:             db.onerror = function(event)
  40:             {
  41:               alert("数据库错误: " + event.target.errorCode);
  42:               console.dir(event.target);
  43:             };
  44:             if(db.objectStoreNames.contains("messageIndexDB"))
  45:             {
  46:                 console.log("contains messageIndexDB");
  47:                 //读写方式开启事务
  48:                 var transaction = db.transaction(["messageIndexDB"],"readwrite");
  49:                 transaction.oncomplete = function(event)
  50:                 {
  51:                     //  console.log("All done!");
  52:                 };
  53:                 transaction.onerror = function(event)
  54:                 {
  55:                     // 错误处理
  56:                     console.dir(event);
  57:                 };
  58:                 var content= document.querySelector("#content");
  59:
  60:                 //得到messageIndexDB的objectStore对象
  61:                 var objectStore = transaction.objectStore("messageIndexDB");
  62:
  63:                 //游标查询
  64:                 objectStore.openCursor().onsuccess = function(event)
  65:                 {
  66:                     //event.target.result获取存储空间的下一个对象
  67:                     var cursor = event.target.result;
  68:                     var flag=0;
  69:
  70:                     //判断是否存在下一个对象,不存在是curson为null
  71:                     if (cursor)
  72:                     {
  73:                           console.log(cursor.key); //获取键
  74:                           console.dir(cursor.value); //实际对象,一个Object实例
  75:                         var msgList= document.querySelector("#messageList");
  76:                         var msgDiv=document.createElement("div");
  77:                         var msgTxt = document.createTextNode(cursor.value[flag]["name"]+"说:"+cursor.value[flag]["content"]);
  78:                         msgDiv.id=cursor.key;
  79:                         msgDiv.appendChild(msgTxt);
  80:                         msgList.appendChild(msgDiv);
  81:                         arrayKey.push(cursor.key);
  82:                         flag++;
  83:                         lastCursor=cursor.key;
  84:                         cursor.continue();   //将游标下移一项
  85:                     }
  86:                     else
  87:                     {
  88:                           console.log("Done with cursor");
  89:                     }
  90:                 };
  91:                 //错误处理
  92:                  objectStore.openCursor().onerror=function(event){
  93:                     console.dir(event);
  94:                 };
  95:             }
  96:         };
  97:
  98:         openRequest.onerror = function (event) {
  99:             // 对request.error做一些需要的处理!
 100:             console.log("your web may not support IndexedDB,please check.");
 101:         };
 102:
 103:         //焦点处理
 104:         document.querySelector("#message").addEventListener("focus",function()
 105:             {
 106:                 this.value = "";
 107:             });
 108:         document.querySelector("#name").addEventListener("focus",function()
 109:             {
 110:                 this.value = "";
 111:             });
 112:
 113:         //添加数据
 114:         document.querySelector("#btn1").addEventListener("click", function()
 115:         {
 116:             var content=document.querySelector("#message").value;
 117:             var name=document.querySelector("#name").value;
 118:             /*var address=document.querySelector("#address").value;*/
 119:             var messageIndexDB=[{"name":name,"content":content}];
 120:
 121:             var transaction = db.transaction(["messageIndexDB"], "readwrite");
 122:             transaction.oncomplete = function(event)
 123:             {
 124:                // console.log("transaction complete");
 125:             };
 126:             transaction.onerror = function(event)
 127:             {
 128:                 console.dir(event);
 129:             };
 130:              //得到messageIndexDB的objectStore对象
 131:             var objectStore = transaction.objectStore("messageIndexDB");
 132:             objectStore.add(messageIndexDB);
 133:             objectStore.openCursor().onsuccess = function(event)
 134:             {
 135:                 cursor = event.target.result;
 136:                 var key;
 137:                 if(lastCursor==null)
 138:                 {
 139:                     key=cursor.key;
 140:                     lastCursor=key;
 141:                 }
 142:                 else
 143:                 {
 144:                     key=++lastCursor;
 145:                 }
 146:                 var msgList= document.querySelector("#messageList");
 147:                 var msgDiv=document.createElement("div");
 148:                 msgDiv.id=key;
 149:                 var msgTxt = document.createTextNode(name+"说:"+content);
 150:                 msgDiv.appendChild(msgTxt);
 151:                 msgList.appendChild(msgDiv);
 152:                 arrayKey.push(key);
 153:                 console.log("success add new record!key:"+key);
 154:                 console.dir(messageIndexDB);
 155:             }
 156:         });
 157:         //删除
 158:         document.querySelector("#delete").addEventListener("click", function()
 159:         {
 160:             if(arrayKey.length==0){
 161:                 console.log("no data to delete!");
 162:             }
 163:             else
 164:             {
 165:                 var transaction = db.transaction(["messageIndexDB"], "readwrite");
 166:                 transaction.oncomplete = function(event)
 167:                 {
 168:                        //    console.log("transaction complete!");
 169:                 };
 170:
 171:                 transaction.onerror = function(event)
 172:                 {
 173:                   console.dir(event);
 174:                 };
 175:                  //得到messageIndexDB的objectStore对象
 176:                 var objectStore = transaction.objectStore("messageIndexDB");
 177:                 var removeKey=arrayKey.shift();
 178:                 //获取key
 179:                 var getRequest=objectStore.get(removeKey);
 180:                 getRequest.onsuccess=function(e)
 181:                 {
 182:                     var result =getRequest.result;
 183:                     console.dir(result);
 184:                 }
 185:                 //删除key
 186:                 var request=objectStore.delete(removeKey);
 187:                 request.onsuccess = function(e)
 188:                 {
 189:                   console.log("success delete record!");
 190:                 };
 191:                 request.onerror = function(e)
 192:                 {
 193:                   console.log("Error delete record:", e);
 194:                 };
 195:                 //隐藏要删除的元素
 196:                 document.getElementById(removeKey).style.display="none";
 197:             }
 198:         });
 199:     }
 200:     window.addEventListener("DOMContentLoaded", init, false);

要注意一点的是,在创建对象存储空间的时候,必须在openRequest.onupgradeneeded 中创建,否则出错

FF4+,和google支持IndexedDB,IE10+据说支持,但LZ测试了,不支持,有错误还请指正。

由于IndexedDB不能实现共享,所以每个客户端打开时IndexedDB保存的数据不一致,LZ是在Google中测试的,打开控制台,查看数据如下

添加留言:

删除留言:

来源:http://www.ido321.com/660.html

时间: 2024-07-31 01:14:00

JavaScript+IndexedDB实现留言板:客户端存储数据的相关文章

《Javascript权威指南》学习笔记之十八:BOM新成就(1)--客户端存储数据(Web SQL DataBase实现)

使用本地存储和会话存储可以实现简单的对象持久化,可以对简单的键值对或对象进行存储.但是,对于比较复杂的关系数据进行处理时,就要用Web SQL Database.浏览器对Web SQL Database的支持情况如图: 一.如何使用Web SQL Database <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-t

HTML5学习笔记之客户端存储数据方法:localStorage(),sessionStorage()

HTML5提供了两种在客户端存储数据的新方法: localStorage():没有时间限制的数据存储 sessionStorage():针对一个session的数据存储 下面的一个例子用localStroage()方法对用户访问页面的次数进行计数 <script type="text/javascript"> if(localStorage.pagecount) { localStorage.pagecount=Number(localStorage.pagecount)+

JavaScript中离线应用和客户端存储(cookies、sessionStorage、localStorage)

一.离线应用 所谓离线web应用,就是在设备不能上网的情况下仍然可以运行的应用. 开发离线web应用需要几个步骤:首先,确保应用知道设备是否能上网,以便下一步执行正确的操作:然后,应用还必须能访问一定的资源(图像.JavaScript.css等),只有这样才能正常工作:最后,必须有一块本地空间用于保存数据,无论能否上网都不妨碍读写. 1.离线检测 HTML5定义一个navigator.onLine属性,这个属性值为true表示设备能上网,值为false表示设备离线. 除了navigator.on

Web Storage 提供的客户端存储数据的方法

包括localStorage和sessionStorage.他们都只能读写当前域的数据,区别是,localStorage存储的数据不会过期,sessionStorage存储的数据每次关闭浏览器后都会被清空. ps: 现在很多浏览器都提供了“匿名访问”,“安全模式”,“隐身窗口”等等功能.在这种情况下,浏览器都是会重新建立一个新的localStorage,所以这些模式下的页面是没法访问在正常模式下的页面中的数据. 曾经,Firefox支持globalStorage:能读写所有域的存储数据的loca

《Javascript权威指南》学习笔记之十七:BOM新成就(1)--客户端存储数据(Storage实现)

1.进入短信界面 2.菜单-设置 3.修改短信中心号码(Set the SIM's smsc number) 保存 [测试结果]:提示保存成功,但是号码没有改变,退出重新进入设置才会看到号码更新 [预期结果]:提示保存成功,号码变为修改过的号码 相关Activity:通过Logcat中I/ActivityManager( 896):我们可以定位到该类-MessagingPreferenceActivity: 相关控件:mSmscPrefList.add(pref); 根据分析我们发现在Messa

H5 客户端存储(Web Storage)

HTML5 提供了两种在客户端存储数据的新方法: localStorage - 本地永久存储,下次打开浏览器数据依然存在 sessionStorage - 只存在于一个会话的数据存储,关闭浏览器数据会被清除 注意: 1)只要清除浏览器cookie,两种存储方式的数据都会被清除 2)对于不同的网站,数据存储于不同的区域,各网站只能访问其自身的数据 3)浏览器之间的数据是各自独立的(比如Firefox中使用localStorage存储一组数据,在Chrome浏览器下是无法读取的) 1.目前大部分的浏

HTML 客户端存储

在客户端存储数据 HTML5 提供了两种在客户端存储数据的新方法: localStorage - 没有时间限制的数据存储 sessionStorage - 针对一个 session 的数据存储 之前,这些都是由 cookie 完成的.但是 cookie 不适合大量数据的存储,因为它们由每个对服务器的请求来传递,这使得 cookie 速度很慢而且效率也不高. 在 HTML5 中,数据不是由每个服务器请求传递的,而是只有在请求时使用数据.它使在不影响网站性能的情况下存储大量数据成为可能. 对于不同的

localStorage_留言板(储存功能)

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>留言本</title><script src="js/jquery-3.2.1.min.js"></script><script type="text/javascript">    $(function(){        //

H5 基于Web Storage 的客户端留言板

<!DOCTYPE html> <html> <head> <meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" /> <meta http-equiv="Content-Type" content="text/html; charset=GBK" /> <title> 客户端留言板 </tit