2017-08-07 96 views
1

當用戶在應用程序上時,我的混合應用程序正在將數據從服務器推送到cordova應用程序。在我的服務器上,我的JSON中有2000個數據。我成功地將2000個數據插入到我的SQLite數據庫中。但是,我意識到該程序插入了與服務器中最後一個數據相同的2000個數據。以下是我的代碼。Cordova SQLite,從服務器獲取值並插入到SQLite數據庫

 $http.get("http://131.4.44.69/php3/fetchSAPInfo.php?key=" + lastSAPOID).success(function (data){ 
       alert(lastSAPOID); 
       if(data == 1){ 
        alert("data is up to date"); 
       }else{ 
        alert("data is updating......"); 

        var i; 
        for(i=0; i<data.length; i++){ 
         var SAP_OID = data[i].SAP_OID; 
         var SAP_Asset = parseInt(data[i].SAP_Asset); 
         var SAP_Description = data[i].SAP_Description; 

         db.transaction(function(tx) { 
          alert(SAP_Asset); 
          tx.executeSql('INSERT INTO SAPInfo VALUES (?,?,?)', [SAP_OID, SAP_Asset , SAP_Description]); 

         }, function(error) { 
          console.log(error); 
         }, function() { 
          alert("insert successfully"); 
         }) 
       } 
      }    
    }).then (function (response){ 
      alert("done and finished"); 
    }); 

我意識到代碼,先去函數先運行db.transaction()函數。因此,該程序不會根據我的for循環獲取JSON數據。我怎麼解決這個問題?

回答

1

我花了一整天的時間弄清楚問題所在。我的for循環必須放入db.transaction()函數內。這是異步編程的問題。以下是我的答案。

 $http.get("http://131.4.44.69/php3/fetchSAPInfo.php?key=" + res).success(function (response){ 
       if(response == 1){ 
        console.log("data is up to date......."); 
       }else{ 
        console.log("data is updating........."); 

        db.transaction(function(tx) { 
        var i; 
         for(i=0; i<response.length; i++){ 
          var SAP_OID = response[i].SAP_OID; 
          var SAP_Asset = parseInt(response[i].SAP_Asset); 
          var SAP_Description = response[i].SAP_Description; 

          tx.executeSql('INSERT INTO SAPInfo VALUES (?,?,?)', [SAP_OID, SAP_Asset , SAP_Description]); 
         } 
        }, function(error) { 
          console.log(error); 
        }, function() { 
          console.log("insert successfully"); 
        }) 
      } 
    }).then (function (response){ 
      console.log("done and finished"); 
    }); 
相關問題