Inserting into HTML5 database with jQuery loop

自闭症网瘾萝莉.ら 提交于 2019-12-25 04:19:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!