2014-04-21 28 views
0

我已經創建了一個數組,它將存儲來自數據庫的動態值。當我在交易功能內打印數組時,它正在打印。當我試圖打印出一面時,我沒有得到價值。我已經在全局聲明瞭這個數組。有什麼問題,我的代碼如下;問題獲取數組值外的函數在JavaScript中?

function sendCategoryDetails() { 

    var selected_category = $('#select-choice :selected').val(); 
    alert("control : " + selected_category); 
    var mycoodinatesDetails; 
    var myLocation = new Array(); 
    var db = window.sqlitePlugin.openDatabase({name: "MYDB"}); 

    db.transaction(function (tx) { 
     tx.executeSql("select Location from Locationlog WHERE Category = '"+selected_category+"';", [], 
      function (tx, res) { 
       for (var i = 0; i < res.rows.length; i++) { 
        myLocation[i] = res.rows.item(i).Location; 
       } 
       alert (myLocation +" length : "+ myLocation.length); // Values are printing 
      }); 
    }); 
    alert (myLocation +" length : "+ myLocation.length); // values are not getting, It showing the length is 0 
} 

有什麼建議嗎?

+1

歡迎來到異步調用的世界。 – Satpal

回答

4

tx.executeSql是一個異步函數。 alert在該函數內工作,因爲這是回調並且異步處理已完成。在函數完成之前觸發函數之後的alert,因此是undefined

解決方案:執行回調中的工作或調用另一個函數,並將數組作爲參數傳遞並在那裏執行工作。

+0

是否可以在另一個tx.executeSql中寫入tx.executeSql?我螞蟻寫數組元素的查詢。我怎樣才能做到這一點 ? – Vinod

+0

你可以在回調中寫另一個'execute'。 – tymeJV