Titanium Studio,JavaScript和SQL错误......无法弄明白

时间:2014-06-26 22:21:59

标签: javascript sqlite titanium-mobile

var url = "http://api.reddit.com/";

var dataArray = [];
var working = function(){
var getData = JSON.parse(this.responseText); 
var titles = getData.data.children;

for(var i=0, j=titles.length; i<j; i++)
{
    var title = titles[i].data.title;
    dataArray.push({
        title: title,
        favorite: 0
    });
    }

    save(dataArray);

}; //working


var save = function(arg){
    console.log(arg);
    var db = Ti.Database.open("newData");
db.execute('CREATE TABLE IF NOT EXISTS redditTitles (id INTEGER PRIMARY KEY, name       TEXT, favorite INTEGER)');
db.execute('INSERT INTO redditTitles (name, favorite) VALUES (?, ?)',  arg.title, arg.favorite);
var rowID = db.lastInsertRowId;
//newRow.id = rowID;
//rows.close();
db.close(); 
gather();
};

var dataContent = [];

var gather = function(){    

var db = Ti.Database.open("newData");
var dbRows = db.execute("SELECT name, favorite FROM redditTitles"); // Returns a Result Set object
while(dbRows.isValidRow()){
    dataContent.push({
        title: dbRows.fieldByName("name"),
        fav: dbRows.fieldByName("favorite")

    });
    console.log("dataContent: "+ dataContent.title);
    dbRows.next();
}
dbRows.close();
db.close();
console.log(dataContent);
userInterAPI();

};

var error = function(){

alert("Please check your network connection and try again.");

};


var client = Ti.Network.createHTTPClient({
onload: working,
onerror: error,
timeout: 5000


});


client.open("GET", url);

client.send();

所以基本上我和我的导师一直在试图弄清楚为什么arg会显示所有数据,但是在保存数据之后我们再去控制台登出它,它会显示为null。不知道为什么。有人请帮助我!

1 个答案:

答案 0 :(得分:1)

您只保存一个项目(错误地 - 这就是未定义的原因)。如果你想保存你需要迭代整个数组的所有东西。

var save = function(arg) {
    console.log(arg);
    var db = Ti.Database.open("newData");

    db.execute('CREATE TABLE IF NOT EXISTS redditTitles (id INTEGER PRIMARY KEY, name       TEXT, favorite INTEGER)');
    db.execute("BEGIN"); // Transaction

    arg.forEach(function(item) {
        db.execute('INSERT INTO redditTitles (name, favorite) VALUES (?, ?)',  item.title, item.favorite);
        //var rowID = db.lastInsertRowId;
    });

    db.execute("COMMIT");

    db.close(); 
    gather();
};

在名为gather的函数中 - 如果要查看所选标题,则应使用:

console.log(dbRows.fieldByName("name"))

或者(这是你想要使用的):

console.log(dataContent[dataContent.length - 1].title)

而不是

console.log(dataContent.title); // dataContent is an Array

*当然,最好避免在每次迭代中使用dataContent.length。这只是一个例子。