首页 > 解决方案 > 从 json 元素获取属性

问题描述

我有一个 json 对象列表,具有以下属性:名字、姓氏和性别。我有一个这样的提取功能:

buttonsend.addEventListener("click", function(){
fetch("http://uinames.com/api/?amount=25&region=denmark&gender=female").then(
    function(response){
        return response.json();
    }
        ).then(function(jsonData){
            for(var i = 0; i <= jsonData.length; i ++){
                console.log(JSON.stringify(jsonData[i]).gender);
            }
            //document.getElementById("json").innerHTML = JSON.stringify(jsonData);

            console.log(2);

        });
    });

在我的 for 循环中,如何访问对象的每个元素,并在我的 HTML 代码中的表格中显示它们?

标签: javascriptjson

解决方案


您的问题的简单解决方案(vanilla ES6):

fetch('http://uinames.com/api/?amount=25&region=denmark&gender=female')
  .then(res => res.json()) // returns response data as JSON object
  .then(jsonData => {
    const destinationTable = document.querySelector('table'); // select table to which you want to append the data
    jsonData.forEach(record => {
      const tr = document.createElement('tr'); // create a table row
      const tdGender = document.createElement('td'); // create a table cell
      tdGender.innerText = record.gender; // insert gender to the created table cell
      tr.appendChild(tdGender); // append table cell to the created row
      destinationTable.appendChild(tr); // append created row to the table
    })
  });

此解决方案假定您在 HTML 文档的某处设置了一个带有正确标题的表格。它遍历服务器返回的记录,并创建包含表格单元格的表格行,其中每个单元格具有性别值。


推荐阅读