2016-07-29 91 views
0

我試圖查詢我的數據庫中的數據。但是,當我查詢我的數據時,我只能在我的最後一次警報(即alert("Total..."))後獲取數據。例如,我運行下面的代碼,「result row:」警報僅在最後一次警報出現後才顯示。我可以知道爲什麼嗎?選擇查詢的順序不正確

function (result) { 

      window.location.href = "#/app/CustHomePage"; 

      var totalBalance = 0; 
      var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0]; 



      for (var i = 0; i < tableRef.rows.length; i++) { 

       alert(tableRef.rows[i].cells[3].innerHTML.substr(1)); 

       var addBalance = parseInt(tableRef.rows[i].cells[3].innerHTML.substr(1)); 
       totalBalance = totalBalance + addBalance; 
      } 

      alert(totalBalance); 
      var myText = result.text; 
      var myTextTwo = myText.replace(/['"]+/g, ''); 
      alert(myTextTwo); 
      var custBal; 



      var myDB = window.sqlitePlugin.openDatabase({ name: "mySQLite.db", location: 'default' }); 

      alert("Hello"); 

      myDB.transaction(function(transaction) { 
       alert("Hello"); 
       transaction.executeSql("SELECT customerBalance FROM customer where nric = '" + myTextTwo + "'", [], function (tx, results) { 
        var len = results.rows.length; 
        for (var i = 0; i < len; i++) { 
         custBal = results.rows.item(i).customerBalance; 
         alert("result row" + results.rows.item(i).customerBalance); 
         alert("CustomerBal" + custBal); 
        } 
       }, 
       function(tx, error) 
       { 

       } 
        ); 
      }); 



      alert("Total after entitled discount: "); 
      alert("Transaction successful, Next Customer Please"); 

     } 
+0

您需要回撥,即使數據庫尚未完成,代碼仍會繼續執行。你的sqlite pull的代碼在哪裏,特別是現在alert所創建的那一行。 –

+0

@PatrickMurphy編輯。 – qcc

回答

0

移動你想要的DB交易已恢復或成功或錯誤處理失敗後發生的事情,我剛搬到出來的參數,並給了他們的名字,以跟蹤它們。然後將您的評論添加到successCallback處理程序的末尾。任何你想在交易失敗後發生的事情都會使用錯誤回調。

function successCallback(tx, results) { 
var len = results.rows.length; 
for (var i = 0; i < len; i++) { 
    custBal = results.rows.item(i).customerBalance; 
    alert("result row" + results.rows.item(i).customerBalance); 
    alert("CustomerBal" + custBal); 
} 


alert("Total after entitled discount: "); 
alert("Transaction successful, Next Customer Please"); 
} 

function errorCallback(tx, error) { 

} 

myDB.transaction(function (transaction) { 
    alert("Hello"); 
    transaction.executeSql("SELECT customerBalance FROM customer where nric = '" + myTextTwo + "'", [], successCallback, errorCallback); 
}); 
+0

如果我們有多個sql語句呢? – qcc

+0

如果您需要在第一次完成後創建第二個sql事務,請將myDB.transaction(sql select code)函數放入成功回調中,在其中創建另一個回調。直到數據返回纔會調用回調 –

+0

你好,這是正確的嗎? https://jsfiddle.net/alvinajh/bftkz6g0/ – qcc