使用 jQuery 循环插入 HTML5 数据库
JavaScript 不是我的强项,所以如果这是非常明显的,请原谅。
我正在编写一些代码,用于创建本地数据库和表、检索 RSS 提要、解析它,并将每个条目的信息添加到数据库中。
$.ajax({
type: "GET",
url: feedurl,
dataType: "xml",
success: parseXml
});
function parseXml(xml){
$(xml).find("item").each(function(){
title = $(this).find("title").text();
description = $(this).find("description").text();
postype = $(this).find("postype").text();
category = $(this).find("category").text();
guid = $(this).find("guid").text();
postid = $(this).find("postid").text();
url = $(this).find("enclosure").attr('url');
db.transaction(function(tx) {
tx.executeSql('INSERT INTO Posts (title, description, postype, category, guid, postid) VALUES (?,?,?,?,?,?)', [title, description,postype,category,guid,postid]);
});
return true;
});
}
问题就在这里。一切都在进行插入查询。插入查询正在插入数据,但每次迭代都使用相同的数据(RSS 提要中的最后一项)。如果我在“title”变量之前添加alert()或将变量附加到div,那么一切都不会出现问题。我不明白。
帮助!
Javascript is not my forte, so excuse me if this is incredibly obvious.
I'm working on some code that creates a local database and table, retrieves an RSS feed, parses it, and adds information from each entry to the database.
$.ajax({
type: "GET",
url: feedurl,
dataType: "xml",
success: parseXml
});
function parseXml(xml){
$(xml).find("item").each(function(){
title = $(this).find("title").text();
description = $(this).find("description").text();
postype = $(this).find("postype").text();
category = $(this).find("category").text();
guid = $(this).find("guid").text();
postid = $(this).find("postid").text();
url = $(this).find("enclosure").attr('url');
db.transaction(function(tx) {
tx.executeSql('INSERT INTO Posts (title, description, postype, category, guid, postid) VALUES (?,?,?,?,?,?)', [title, description,postype,category,guid,postid]);
});
return true;
});
}
Here's the issue. Everything is working up to the insert query. The insert query is inserting data but it uses the same data (the last item in the RSS feed) every iteration. If I add alert() right before the 'title' variable or append the variables to a div, it all works without a problem. I don't get it.
Help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事务需要花费一点时间,并且您通过在声明中缺少
var
关键字来共享一些全局变量。添加var
以便循环迭代作为它自己的变量集应该可以解决问题:The transactions take a slight amount of time, and you're sharing some global variables by missing the
var
keyword on your declarations. Addingvar
so iterations of the loop as it's own variable set should fix the issue:您忘记了
var
!You forgot
var
!