2015-02-24 38 views
1

我目前正在研究phonegap應用程序,它必須與遙遠的mysql服務器同步。試圖從Json插入到websql表中,使用每個()

我使用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 
     }); 

    }); 
}); 

我的代碼可能是可怕的,我還是個「新手」。無論如何,先謝謝你了,對不起我的英文不好。

回答

1

事務意味着一次處理對數據庫的許多請求。不要啓動多個事務,請嘗試對所有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]); 
      } 
     }); 
    }); 
} 

當開始一個事務中的數據庫/表被鎖定了該實例。如果你打電話多次交易,首先鎖定一切,其餘的不能完成。

此外,我已經取代了.eachfor,因爲在使用for超過.each

+0

謝謝您的答覆很大的性能增益。我試過你的代碼,但它不會在我的websql數據庫中插入任何東西。我知道爲什麼。我還用「.lenght」取代了「.lenght()」,因爲它顯示我一個錯誤(數字不是函數)。我不知道。每個人都感謝。 – riri 2015-02-24 16:09:09

+0

我已經更新了這個例子,它又是一個例子,你可能無法複製粘貼它。我注意到表名是'projets',可能是一個錯字。我還修復了'length'問題並更新'executeSql'來轉義輸入值。這些更新現在可能適用於您。 – 2015-02-24 16:58:51

+0

經過一些修正後,感謝它! 'projets'上沒有錯字錯誤,實際上是我的表名(它是法語項目)。同樣在'imgName'聲明中,我對'imgurl.lastIndexOf('/'))'有一些問題''我用'imgurl.lastIndexOf('/'))'替換了它,它運行良好。再次感謝你 ! – riri 2015-02-24 17:08:12