数据库是属于服务器的,这是天经地义的事,但是有时候数据也许并非需要存储在服务器,但是这些数据也是一条一条的记录,怎么办?今天来带领你领略一下H5的一个新特性--indexedDB的风骚。你会情不自禁的发出感叹--不可思议!一、链接数据库 indexedDB没有创建数据库的概念, ...
数据库是属于服务器的,这是天经地义的事,但是有时候数据也许并非需要存储在服务器,但是这些数据也是一条一条的记录,怎么办?今天来带领你领略一下H5的一个新特性--indexedDB的风骚。你会情不自禁的发出感叹--不可思议!
一、链接数据库
indexedDB没有创建数据库的概念,你可以直接链接数据库,如果你链接的数据库并不存在,那么会自动的创建一个数据库。看下面的这个例子。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title></head><body> <button type="" id='conbtn'>链接数据库</button><script> // In the following line, you should include the prefixes of implementations you want to test. window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; // DON'T use "var indexedDB = ..." if you're not in a function. // Moreover, you may need references to some window.IDB* objects: window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction; window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange // (Mozilla has never prefixed these objects, so we don't need window.mozIDB*) function connectDB(name,version,success,error){ let dbConnect = indexedDB.open(name,version); dbConnect.onsuccess = function(e){ console.log('数据库链接成功!'); success(e.target.result); } dbConnect.onerror = function(e){ console.log('数据库链接失败!'); error(e); } dbConnect.onupgradeneeded = function(e){ success(e.target.result); let oldVersion = e.oldVersion; let newVersion = e.newVersion; console.log('数据库更新成功,旧的版本号为:'+oldVersion+",新的版本号为:"+newVersion); } } window.onload=function(){ let btn = document.getElementById('conbtn'); btn.onclick = function(){ connectDB('haha',1,function(){ console.log('链接成功,或者更新成功回调函数'); },function(){ console.log('链接失败回调函数!') }); } }</script></body></html>
原标题:将数据库从服务器移到浏览器
关键词:数据库
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。