首页 > 解决方案 > 从 objectstore 获取项目在 HTML 中返回 [object Object]

问题描述

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

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

我怀疑 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

                }
            }   
        }
    }
}

标签: javascriptarraysobjectecmascript-6indexeddb

解决方案


使用JSON.stringify

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

推荐阅读