javascript - 从 json 元素获取属性

标签 javascript 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 代码的表格中?

最佳答案

问题的简单解决方案(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 文档中的某处有一个带有正确标题设置的表格。它遍历服务器返回的记录,并创建包含每个记录的性别值的表格单元格的表格行。

关于javascript - 从 json 元素获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52571828/

相关文章:

javascript - 读取JSON文件,解析并导入到Parse

javascript - 2 与数据库相关的下拉菜单

javascript - jQuery 事件优先级

javascript - 如何包含 gl-matrix?

javascript - 我在安装 npm 模块时遇到问题

javascript - 我究竟如何从这个巨大的 JSON 对象中获取单个值?

javascript - Extjs 6 - 如何在网格中使用 DataIndex 来获取嵌套数据

java - 使用 Lambda、Stream java 将值添加到两个嵌套的 JSON 数组中

javascript - 如何使用 javascript jquery 在 html 页面中显示 json(数组)响应

javascript - 从 firebase 数据库检索数据