2012-10-24 71 views
0

真的很遺憾,不得不求助於問一個論壇上的問題,但我一直在敲打我的腦袋整天試圖解決這一問題。PhoneGap的寫SQLite表

我有創建SQLite數據庫,創建表,獲取從tinternet一個JSON進料,然後將該數據送入表中的PhoneGap應用程序。

一切似乎是確定,直到該數據庫是應該填充位。 「insertProperty」函數不運行。任何幫助將非常棒!

下面是相關的代碼片段。

x$(document).on('deviceready', function() { 

    // CREATE DATABASE 
var localDatabase = window.sqlitePlugin.openDatabase("localDB", "1.0", "Local DB", 5000000); 
console.log("Database Loaded"); 
// CREATE properties TABLE 
var query = "CREATE TABLE IF NOT EXISTS properties (propertyid INT, propertytype text, address text, postcode text, clientid INT);" 
db.transaction(function (trxn) { 
    trxn.executeSql(query, [], callback, 
    function (transaction, error) { //error callback 
     console.log(error); 
    }); 
}); 
} 



function insertProperty(db, data) { 
var query = "INSERT INTO properties (propertyid, propertytype, address, postcode, clientid) VALUES (?,?,?,?,?);" 
db.transaction(function (trxn) { 
    trxn.executeSql(query,[data.propertyid, data.propertytype, data.address, data.postcode, data.clientid], 
    function (transaction, resultSet) { 
     console.log('success'); 
    }, 
    function (transaction, error) { 
     console.log(error); 
    } 
    ); 
}); 
} 




x$().xhr("http://myurl.com", { // GET JSON FEED 

    async: true,callback: function() { try { 
     var dataArray = JSON.parse(this.responseText); // PARSE JSON FEED 
     console.log("Loading live data"); 
     dataArray.forEach(function (thedata) { // LOOP DATA 
      console.log(thedata.address); 
      insertProperty(localDatabase, thedata); 
     }); 
     console.log("Rendering Live Data"); 
     renderDataset(dataArray) 
    } catch (e) { // failed to retrieve data 
      console.log("There was a problem, Loading local data"); 
      getStoredProperties(localDatabase, function (offlineData) { 
       renderDataset(offlineData); 
      }); 
     } 
    } 
}); 

該腳本運行至「console.log(thedata.address);」並向我顯示一個地址,但是當它嘗試運行insertProperty函數時,它會保留並直接轉到「console.log(」存在問題,加載本地數據「);」位。再次

感謝您的幫助,您可以提供。 Dan

回答

0

顯然你在「deviceready」函數的作用域中定義了局部變量localDatabase,因此當你在xhr回調函數中循環數據時它是不可訪問的。

+0

真棒!謝謝Zvona,我現在覺得自己很笨拙!至少它現在工作我聲明window.localDatabase而不是var = localDatabase ... – Dan

+0

只是一個問題Zvona - 腳本現在運行正常,但我在調用insertProperty函數時出現錯誤。 {「message」:「SQL語句錯誤:沒有這樣的表:屬性」} 我猜表格沒有被創建,但我不知道爲什麼......我將事務改爲localDatabase.transation(function (txrn){但沒有幫助... – Dan

+0

您需要直接執行deviceready回調。現在你執行XHR內的每個功能(甚至X $()。XHR)和deviceready發生前的回調可能被解僱。 – zvona