构建web应用程序的新手。如果你有什么好的资源,请建议你阅读一些资源!
问题:我已经在AWS上创建了一个调用API-https://tnmw5vn267.execute-api.us-east-1.amazonaws.com/dev输出是一个JSON对象。
然而,我不知道如何将其放入HTML页面(即如何将JSON对象放入HTML中,然后将其显示为表(,只有:
`函数CreateTableFromJSON(({var myEmployees=[{"FirstName":"Benjamin";,"姓氏":"谭;}]
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < myEmployees.length; i++) {
for (var key in myEmployees[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < myEmployees.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myBooks[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}`
上面只生成一个静态表,该表不会根据我的API输出进行更新。不知道怎么做?
以下是我如何使用普通JS来处理它。
-
使用
fetch
从API获取数据。 -
使用模板文字使用
map
和join
构建HTML字符串序列。 -
将最后一个字符串添加到页面中。
const json = '[{"LatestGreetingTime":"2021-06-19T15:47:10.539Z","ID":"Hello from Lambda, Benjamin Tan","FirstName":"Benjamin","LastName":"Tan"},{"LatestGreetingTime":"2021-06-19T13:44:33.761Z","ID":"Hello from Lambda, ichal shodin","FirstName":"ichal","LastName":"shodin"},{"LatestGreetingTime":"2021-06-19T13:44:33.761Z","ID":"Hello from Lambda, victoria Lovelace","FirstName":"victoria","LastName":"Lovelace"}]';
// This simulates a call to your API
function mockFetch() {
return new Promise((res, rej) => {
setTimeout(() => res(json), 1000);
});
}
// Grab the button, and a div where you can place the table
const button = document.querySelector('button');
const div = document.querySelector('div');
// Add an event listener to your button that
// callApi when it's clicked
button.addEventListener('click', callApi, false);
// As mentioned the comments you should be using
// the fetch API here, and it would look like
// fetch(url).then(res => res.json).then(buildTable)
function callApi() {
mockFetch()
.then(res => JSON.parse(res))
.then(buildTable);
}
// This function takes the data, extracts the headings
// from the first object, and then builds the row data.
// It finally puts everything together as a template literal
// and adds it to the div
function buildTable(data) {
const headings = buildHeadings(Object.keys(data[0]));
const rows = buildRows(data);
div.innerHTML = `<table><thead>${headings}</thead><tbody>${rows}</tbody></table>`;
}
// Iterate over the headings array and return heading HTML
function buildHeadings(headings) {
return headings.map(heading => `<th>${heading}</th>`).join('');
}
// Iterate over the data return row HTML
function buildRows(data) {
return data.map(row => `<tr>${buildCells(row)}</tr>`).join('');
}
// Iterate over the row data and return cell HTML
function buildCells(row) {
return Object.values(row).map(cell => `<td>${cell}</td>`).join('');
}
table { border-collapse: collapse; padding 0.2em; }
td { padding: 0.5em }
<button>Call API</button>
<div />
让我向您展示解决方案。首先,您需要通过fetch函数从API获取JSON。之后,您需要通过.ninnerHTML将其放在特定的HTML元素中
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
</head>
<body>
<script>
async function fetchDataAndRenderTable() {
const serverURL = 'https://tnmw5vn267.execute-api.us-east-1.amazonaws.com/dev'
const dataFromTheServer = await fetch(serverURL).then(res => res.json())
const tableHTMLElement = document.createElement('table')
tableHTMLElement.innerHTML = `
<table style="width:100%">
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
${
dataFromTheServer.map(item => {
return `
<tr>
<td>${item.FirstName}</td>
<td>${item.LastName}</td>
</tr>
`
})
}
</table>
`
document.body.appendChild(tableHTMLElement)
}
fetchDataAndRenderTable()
</script>
</body>
</html>
PS。但是您的API需要允许CORS,否则您将无法从浏览器中获取它