gpt4 book ai didi

javascript - 如何将 JSON 数据添加到 HTML 表格

转载 作者:行者123 更新时间:2023-12-02 23:57:28 26 4
gpt4 key购买 nike

目前,我正在获取数据,一旦收到数据,我需要将其添加到 HTML 表中。

我尝试了一些方法,但无法在页面加载后动态添加数据。

我想使用 Javascript 或 jQuery 添加它

这是 HTML 结构:

<div>
<table cellspacing="0" cellpadding="0">
<thead>
<tr>
<th scope="col"><span>Email</span></th>
<th><span>Last Name</span></th>
<th><span>First Name</span></th>
<th><span>Role</span></th>
<th><span>Cell Phone User</span></th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row" data-label="Email"></td>
<td data-label="Last Name"></td>
<td data-label="First Name"></td>
<td data-label="Role"></td>
<td data-label="Cell Phone User"></td>
</tr>
</tbody>
</table>
</div>

以下是获取数据后的外观示例:

[{
"id": 1,
"email": "janedoe@example.com",
"familyName": "Doe",
"givenName": "Jane",
"role": "admin",
"smsUser": true
},
{
"id": 2,
"email": "johndoe@example.com",
"familyName": "Doe",
"givenName": "John",
"role": "standard",
"smsUser": false
}]

这是我迄今为止尝试过的:

这是我的事件监听器,用于在页面加载后加载数据:


window.path = "http://localhost:3000/users";

// getUsers function plus any additional functions go here ...
const getUsers = options => {
let url = new URL(window.path);
if (options) {
url.search = new URLSearchParams(options)
}
return Promise.resolve(fetch(url))
}

document.addEventListener('DOMContentLoaded', () => {

/* SELECT DOM ELEMENTS*/
let table = document.querySelector('tbody');

let promise = getUsers({page=2, role:'admin'})

.then(data => {

var html = '<table>';
for( var j in data[0] ) {
html += '<th>' + j + '</th>';
}
html += '</tr>';

for( var i = 0; i < data.length; i++) {
html += '<tr>';
for( var j in data[i] ) {
html += '<td>' + data[i][j] + '</td>';
}
}
html += '</table>';
table.appendChild(html)

return table;
})
.catch(err => {
console.log('Error fetching from /users', err);
return null
})

})



感谢任何帮助。

最佳答案

第一个问题是该行

let promise = getUsers({page=2, role:'admin'})

应该是

let promise = getUsers({page:2, role:'admin'})

其次,appendChild不接受字符串,而是接受 DOM 元素。对于这种情况,请改用innerHTML。

第三,您使用 querySelect 来查找 '<tbody>'元素因此开始构建内部 html 标签 '<tr>'不是'<table>'

const getUsers = async options => ([
{
id: 1,
email: "janedoe@example.com",
familyName: "Doe",
givenName: "Jane",
role: "admin",
smsUser: true
},
{
id: 2,
email: "johndoe@example.com",
familyName: "Doe",
givenName: "John",
role: "standard",
smsUser: false
}
]);

document.addEventListener('DOMContentLoaded', async () => {
const table = document.querySelector('tbody');
const users = await getUsers({ page:2, role:'admin' });
const userToTableRow = user => [
{ attrs: 'scope="row" data-label="Email"', propName: 'email'},
{ attrs: 'data-label="Last Name"', propName: 'familyName'},
{ attrs: 'data-label="First Name"', propName: 'givenName'},
{ attrs: 'data-label="Role Name"', propName: 'role'},
{ attrs: 'data-label="Cell Phone User"', propName: 'smsUser'},
].map(mapper => (
`<td ${mapper.attrs}>${user[mapper.propName]}</td>`
)).join('');

const html = users.map(user =>
`<tr>${userToTableRow(user)}</tr>`
).join('');
table.innerHTML = html;
});
<div>
<table cellspacing="0" cellpadding="0">
<thead>
<tr>
<th scope="col"><span>Email</span></th>
<th><span>Last Name</span></th>
<th><span>First Name</span></th>
<th><span>Role</span></th>
<th><span>Cell Phone User</span></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

编辑:我喜欢上面第一个实现中的 async/await 。 async只是强制函数将返回值包装在 Promise 中的一种简便方法。 await只是一种新的语言方式来解决内联 promise ,而无需使用 .then((res) => {...})await只能用于 async功能。

解决评论中的问题。我提交的替代解决方案是:

  • 不使用asyncawait
  • 模拟fetch而不是getusers
  • 使用 document.createElement() 和appendChild 而不是仅仅设置 innerHTML内容。

const getUsersUrl = 'http://localhost:3000/users';

function mockFetch(url) {
const stubbedResponse = JSON.stringify([
{
id: 1,
email: "janedoe@example.com",
familyName: "Doe",
givenName: "Jane",
role: "admin",
smsUser: true
},
{
id: 2,
email: "johndoe@example.com",
familyName: "Doe",
givenName: "John",
role: "standard",
smsUser: false
}
]);

return Promise.resolve({
json() {
return Promise.resolve(JSON.parse(stubbedResponse));
}
});
}

const getUsers = options => {
let url = new URL(getUsersUrl);
if (options) {
url.search = new URLSearchParams(options)
}
return mockFetch(url);
}

const userToTableRow = user => {
const tr = document.createElement('tr');
[
{
attrs: {
scope: 'row',
'data-label': 'Email'
},
propName: 'email'
},
{
attrs: { 'data-label': 'Last Name' },
propName: 'familyName'
},
{
attrs: { 'data-label': 'First Name' },
propName: 'givenName'
},
{
attrs: { 'data-label': 'Role Name' },
propName: 'role'
},
{
attrs: { 'data-label': 'Cell Phone User' },
propName: 'smsUser'
},
].map(mapper => {
const td = document.createElement('td');
for (const [attrName, attrValue] of Object.entries(mapper.attrs)) {
td.setAttribute(attrName, attrValue);
}
td.appendChild(document.createTextNode(user[mapper.propName]));
return td;
}).forEach(td => { tr.appendChild(td); });
return tr;
}

document.addEventListener('DOMContentLoaded', () => {
const table = document.querySelector('tbody');
getUsers({ page:2, role:'admin' })
.then(response => response.json())
.then(users => {
users
.map(user => userToTableRow(user))
.forEach(tr => { table.appendChild(tr); });
});
});
<div>
<table cellspacing="0" cellpadding="0">
<thead>
<tr>
<th scope="col"><span>Email</span></th>
<th><span>Last Name</span></th>
<th><span>First Name</span></th>
<th><span>Role</span></th>
<th><span>Cell Phone User</span></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

关于javascript - 如何将 JSON 数据添加到 HTML 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55307957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com