从对象库中获取项目将以HTML形式返回[对象对象]

时间:2019-05-29 12:44:39

标签: javascript arrays object ecmascript-6 indexeddb

现在,我正在遍历对象存储“ tasksStore”中的所有对象。当我尝试将对象嵌入到HTML中时,它仅返回[object Object]。如果我尝试指定要检索的对象的一部分(例如getTasks.result.title),它将返回未定义的内容。

我不太确定自己在做什么错。当我控制台记录结果时,我得到对象信息的“正常”返回: image

我怀疑put和get的数据类型崩溃了,但是经过一番挖掘之后似乎并不是问题所在。

Javascript:

function listTask() {
    //open connection to database
    let request = window.indexedDB.open("KanbanDatabase", 2), 
    db,
    tx,
    store,
    index;

    //error handler on connection
    request.onerror = function(e) {
        console.log("There was en error listing tasks: " + e.target.errorCode);
    }

    //success handler on connection
    request.onsuccess = function(e) {
        console.log("Successfully listed tasks");
        db = request.result;

        //define transaction, store and index
        tasksTx = db.transaction("tasksStore", "readwrite");
        tasksStore = tasksTx.objectStore("tasksStore");
        tasksIndex = tasksStore.index("title", "status");

        //error handler on result of the request
        db.onerror = function(e) {
            console.log("ERROR " + e.target.errorCode);
        }

        //variable for counting objects in the index
        let amountOfTasks = tasksIndex.count();

        //error handler
        amountOfTasks.onerror = function() {
            console.log("There was an error finding the amount of tasks")
        }

        //success handler
        amountOfTasks.onsuccess = function() {
            //console.log("Tasks: " + amountOfTasks.result);
            //TODO: add destination to the function to be able to list tasks with the specific statuses
            for (var i = 0; i < amountOfTasks.result+1; i++) {
                let getTasks = tasksStore.get(i);

                let getTasksElementContainer = document.getElementById("list-tasks");
                let createTasksList = document.createElement("li");
                createTasksList.id = "task-" + i;

                getTasks.onerror = function() {
                    console.log("There was an error looping through the tasks")
                }

                getTasks.onsuccess = function() {

                    console.log(getTasks.result);
                    getTasksElementContainer.appendChild(createTasksList);
                    createTasksList.innerHTML = getTasks.result;
                    //createTasksList.innerHTML = getTasks.result.title - does not work, returns undefined

                }
            }   
        }
    }
}

1 个答案:

答案 0 :(得分:0)

使用JSON.stringify

getTasksElementContainer.appendChild(JSON.stringify(createTasksList));