通过API迭代json对象



在表中需要显示从请求中的链接链接到的一些用户的数据。我首先得到XMLRequest并设置RequestHeader。

在函数show中,我正在为用户的属性创建标签。我有一个用户数据的问题,需要在下面显示。我不明白在td标签中打印未定义的问题是什么。

数据的原型是Object。

<script>
var request = new XMLHttpRequest();
request.open("GET","https://dummyapi.io/data/v1/user")
request.setRequestHeader("app-id","6176d770ceedfe1a52297285");
request.onreadystatechange = async function () {
var json = JSON.parse(request.responseText);
var f = json.data;
var obj = Object.assign({},json.data);
console.log(obj);
show(obj);
}
request.send();
function show(data) {
let tab =
`<tr>
<th>Id</th>
<th>Title</th>
<th>First Name</th>
<th>Last Name</th>
<th>Picture</th>
</tr>`;

for (var r in data) {
tab += `<tr>
<td>${r.id} </td>
<td>${r.title}</td>
<td>${r.firstName}</td>
<td>${r.lastName}</td>
<td>${r.picture}</td>

</tr>`;
}
document.getElementById("employees").innerHTML = tab;
}
// show(data);
</script>

<h1>Registered Employees</h1>
<table id="employees"></table>
</body>

使用fetch更容易做到

const tEmployees = document.querySelector('#employees tbody')  
fetch('https://dummyapi.io/data/v1/user', { method: 'GET', headers: { 'app-id': '6176d770ceedfe1a52297285' } })
.then( res => res.json())
.then( employees =>
{
employees.data.forEach(emp => 
{
let newRow = tEmployees.insertRow()
newRow.insertCell().textContent = emp.id
newRow.insertCell().textContent = emp.title
newRow.insertCell().textContent = emp.firstName
newRow.insertCell().textContent = emp.lastName
newRow.insertCell().innerHTML   = `<img src="${emp.picture}" alt="${emp.firstName} – ${emp.lastName}" width="72" height="72">` 
})
})
.catch((error) =>  console.error('Error:', error) )
body {
font-family : Arial, Helvetica, sans-serif;
font-size   : 14px;
}
table  {
border-collapse : collapse;
margin          : 2em 1em;
}
td,th  {
padding    : .2em .8em;
border     : 1px solid darkblue;
}
thead { 
background-color: steelblue;
}
<h1>Registered Employees</h1>
<table id="employees">
<thead>
<tr> <th>Id</th> <th>Title</th> <th>First Name</th> <th>Last Name</th> <th>Picture</th> </tr>
</thead>
<tbody></tbody>
</table>

最新更新