我想用phonegap在web sql中做一些数据初始化。
下面是我的代码的一部分,当初始化表时,它总是进入错误回调。我没找到原因。
可以直接在浏览器中测试。
<!DOCTYPE HTML>
<html>
<head>
<title>Cordova</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
var db = null;
//document.addEventListener("deviceready", onDeviceReady, false);
$(document).ready(function(){
onDeviceReady();
});
function errorCB(tx, err) {
alert("Error processing SQL: "+err);
}
function successCB() {
console.log("success!");
}
function onDeviceReady() {
var dBVersion = localStorage.getItem("db_version");
if(dBVersion == null){
db = initDB();
//init table, set db_version to local storage
db.transaction(initTable, errorCB, function(){localStorage.setItem("db_version","1.0");});
}else{
db = openDatabase('beauty', dBVersion, 'test offline database', 200000);
}
}
function initDB(){
var myDB = null;
try {
if (!window.openDatabase) {
alert('db init failed');
} else {
var shortName = 'beauty';
var version = '1.0';
var displayName = 'test offline database';
var maxSize = 200000;
myDB = openDatabase(shortName, version, displayName, maxSize);
}
} catch(e) {
console.log(e);
if (e.name == "INVALID_STATE_ERR") {
console.log("Invalid database version.");
} else {
alert("Unknown error "+e+".");
}
}
return myDB;
}
function initTable(tx){
$.getJSON("data.json",function(data){
tx.executeSql('CREATE TABLE IF NOT EXISTS images (id INTEGER PRIMARY KEY, url TEXT, tag TEXT, type TEXT,status TEXT, unlocktime INTEGER, favorite INTEGER, phase INTEGER,other TEXT)');
for(var i=0; i<data.length; i++){
tx.executeSql('insert into images values ('+ data[i].id +',"' + data[i].url +'","' + data[i].tag +'","'+ data[i].type +'","' + data[i].status + '",' +data[i].unlocktime+','+data[i].favorite+','+data[i].phase+',"'+ data[i].other +'");');
}
console.log("init ok!");
});
}
</script>
</head>
<body>
<input type="button" value="Get Image" onclick="test()" /> <br/>
</body>
</html>
json文件就像
[
{
"id": 101001,
"url": "img/1.jpg",
"tag": "other",
"type": "local",
"status": "normal",
"unlocktime": 0,
"favorite": 0,
"phase": 1,
"other": ""
},
{
"id": 101002,
"url": "img/2.jpg",
"tag": "other",
"type": "local",
"status": "normal",
"unlocktime": 0,
"favorite": 0,
"phase": 1,
"other": ""
}
]
我使用 Chrome 测试。它警告“错误处理 SQL:未定义”。请帮助找出错误的地方。