尝试使用 each() 从 Json 插入 websql table
Trying to insert into websql table from Json, using each()
我目前正在开发 phonegap 应用程序,它必须与远程 mysql 服务器同步。
我使用 getJson() 加载了一个 json 文件,并将这些行插入到 websql 数据库中。我的问题是只有第一行被插入到 websql 数据库中。我实际上在 Json 文件中有两行。
这是我的函数:
function loadJson(){
$.getJSON( "http://localhost:8888/results.json", function( data ) {
$.each(data, function(i, item) {
var title=data[i].title;
var content=data[i].content;
var imgurl=data[i].imgurl;
imgName = imgurl.substring(imgurl.lastIndexOf('/'))
db.transaction(function (transaction) {
console.log('we insert' + title); // It works, display me the two different title
transaction.executeSql('INSERT INTO projets (title, content, imgurl) VALUES ("' + title + '","' + content + '", "' + imgurl + '" );'); //Only the first row is inserted
});
});
});
我的代码可能很糟糕,我还是"newbie"。无论如何,提前谢谢你,抱歉我的英语不好。
事务旨在一次处理对数据库的许多请求。不要启动多个事务,而是尝试对所有 SQL 个语句使用一个事务。
示例(可能需要一些改进):
function loadJson(){
$.getJSON( "http://localhost:8888/results.json", function( data ) {
db.transaction(function (transaction) {
var len = data.length;
for(var i = 0; i < len; i++) {
var title=data[i].title;
var content=data[i].content;
var imgurl=data[i].imgurl;
imgName = imgurl.substring(imgurl.lastIndexOf('/'));
console.log('we insert' + title); // It works, display me the two different title
transaction.executeSql('INSERT INTO projets (title, content, imgurl) VALUES (?,?,?)',[title, content, imgurl]);
}
});
});
}
启动事务时,database/table 会为该实例锁定。如果您调用多个事务,第一个锁定所有内容,其余的将无法完成。
此外,我已将 .each
替换为 for
,因为使用 for
比 .each
性能更高
我目前正在开发 phonegap 应用程序,它必须与远程 mysql 服务器同步。
我使用 getJson() 加载了一个 json 文件,并将这些行插入到 websql 数据库中。我的问题是只有第一行被插入到 websql 数据库中。我实际上在 Json 文件中有两行。
这是我的函数:
function loadJson(){
$.getJSON( "http://localhost:8888/results.json", function( data ) {
$.each(data, function(i, item) {
var title=data[i].title;
var content=data[i].content;
var imgurl=data[i].imgurl;
imgName = imgurl.substring(imgurl.lastIndexOf('/'))
db.transaction(function (transaction) {
console.log('we insert' + title); // It works, display me the two different title
transaction.executeSql('INSERT INTO projets (title, content, imgurl) VALUES ("' + title + '","' + content + '", "' + imgurl + '" );'); //Only the first row is inserted
});
});
});
我的代码可能很糟糕,我还是"newbie"。无论如何,提前谢谢你,抱歉我的英语不好。
事务旨在一次处理对数据库的许多请求。不要启动多个事务,而是尝试对所有 SQL 个语句使用一个事务。
示例(可能需要一些改进):
function loadJson(){
$.getJSON( "http://localhost:8888/results.json", function( data ) {
db.transaction(function (transaction) {
var len = data.length;
for(var i = 0; i < len; i++) {
var title=data[i].title;
var content=data[i].content;
var imgurl=data[i].imgurl;
imgName = imgurl.substring(imgurl.lastIndexOf('/'));
console.log('we insert' + title); // It works, display me the two different title
transaction.executeSql('INSERT INTO projets (title, content, imgurl) VALUES (?,?,?)',[title, content, imgurl]);
}
});
});
}
启动事务时,database/table 会为该实例锁定。如果您调用多个事务,第一个锁定所有内容,其余的将无法完成。
此外,我已将 .each
替换为 for
,因为使用 for
比 .each