问题
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!
回答1:
The transactions take a slight amount of time, and you're sharing some global variables by missing the var
keyword on your declarations. Adding var
so iterations of the loop as it's own variable set should fix the issue:
function parseXml(xml){
$(xml).find("item").each(function(){
var $this = $(this),
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]);
});
});
}
回答2:
You forgot var!
来源:https://stackoverflow.com/questions/3936732/inserting-into-html5-database-with-jquery-loop