javascript - 从 json 元素获取属性
问题描述
我有一个 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 文档的某处设置了一个带有正确标题的表格。它遍历服务器返回的记录,并创建包含表格单元格的表格行,其中每个单元格具有性别值。
推荐阅读
- c++ - 为 OLED SSD1306 编写包装器
- python - 在 tkinter 中嵌入 matplotlib:鼠标悬停时图形会四处移动
- r - 军官 R - 从不同目录中选择具有相同名称的图像时重复图像打印
- r - 如何使用向量的值对多维列联表进行子集化(即每个值指定一个维度)?
- java - Java - 对泛型 X 的引用应该被参数化
- java - 添加 Java JNI -Xcheck:jni 选项以在 Android Studio 中运行命令
- here-api - 使用 here-api 查找门牌号为 17 1/2 的地址
- python - AttributeError: 'NoneType' object has no attribute 'send' ,当我尝试将带有机器人的消息发送到特定的不和谐频道时
- pine-script - 回测 - 如果在上一次收盘和新交易之间没有发生条件,则不开仓
- javascript - MongoDB 使用聚合管道计算单个用户的所有喜欢和帖子