簡體   English   中英

如何在 console.log 中顯示輸出?

[英]How can I show the output in console.log?

我正在嘗試從 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>

innerHTML 可以實現。

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => {
  console.log(json);
  document.getElementById("console").innerHTML += JSON.stringify(json)}
  )

如果您只想將數據輸出為格式化字符串,您可以創建一個函數來使用<pre><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>

如果您想以不同的方式顯示數據(例如在表格中),您可以迭代( mapObject.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. `join` the array elements up // into one string once the iteration is complete. const rows = entries.map(([key, value]) => { return ` <tr> <td class="heading">${key}</td> <td>${value}</td> </tr> `; }).join(''); // Create a new HTML string const html = `<table><tbody>${rows}</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>

添加文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM