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。不知道为什么。有人请帮助我!
最佳答案
您仅保存一项(不正确-这就是未定义的原因)。如果要保存所有内容,则必须遍历整个数组。
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
。这只是一个例子。