我正在嘗試從 api 獲取資料到控制臺,然后將其顯示在頁面上。
我已正確地將占位符 api 中的資料提取到 console.log 中,但無法將其顯示到 div 中的頁面上。我究竟做錯了什么?
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
document.getElementById("console")
<div id="console"></div>
uj5u.com熱心網友回復:
innerHTML 可以實作。
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
console.log(json);
document.getElementById("console").innerHTML = JSON.stringify(json)}
)
uj5u.com熱心網友回復:
如果您只想將資料輸出為格式化字串,您可以創建一個函式來使用<pre>and來“漂亮地列印”字串化資料<code>。
const output = document.querySelector('.output');
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(updateHTML);
function updateHTML(data) {
const json = JSON.stringify(data, null, 2);
const html = `<pre><code>${json}</code></pre>`;
output.insertAdjacentHTML('beforeend', html);
}
<div class="output"></div>
如果您想以不同的方式顯示資料(例如在表格中),您可以迭代 ( map) 回傳的鍵和值Object.entries以回傳一行 HTML 字串,并將該 html 添加到頁面。
const output = document.querySelector('.output');
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(updateHTML);
function updateHTML(data) {
// Get the object entries - and array of key/value pairs
const entries = Object.entries(data);
// Iterate over the entries and return a new array
// of strings created from the key/value using a
// template string.
const rows = entries.map(([key, value]) => {
return `
<tr>
<td >${key}</td>
<td>${value}</td>
</tr>
`;
});
// Create a new HTML string by `join`ing up the row array
// and adding it to a new string
const html = `<table><tbody>${rows.join('')}</tbody></table>`;
// Insert the HTML into the page
output.insertAdjacentHTML('beforeend', html);
}
table { background-color: #efefef; border-collapse: collapse; border: 1px solid #afafaf; }
td { padding: 0.4em; border: 1px solid white; }
.heading { text-transform: uppercase; text-align: right; font-weight: 500; background-color: #dfdfdf; }
<div class="output"></div>
添加檔案
模板/字串文字
joininsertAdjacentHTML
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/339662.html
