我有一个 json 对象列表,其属性为:名字、姓氏和性别。 我有一个这样的获取函数:
buttonsend.addEventListener("click", function(){
fetch("http://uinames.com/api/?amount=25®ion=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®ion=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/