简体   繁体   English

如何在 console.log 中显示输出?

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

I am trying to fetch data from an api into console and then display it on a page.我正在尝试从 api 获取数据到控制台,然后将其显示在页面上。

I have correctly fetched the data from the placeholder api into console.log, but I cannot display it onto the page in the div.我已正确地将占位符 api 中的数据提取到 console.log 中,但无法将其显示到 div 中的页面上。 What am I doing wrong?我究竟做错了什么?

 fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(json => console.log(json)) document.getElementById("console")
 <div id="console"></div>

innerHTML could achieve. innerHTML 可以实现。

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

If you just want to output the data as a formatted string you could create a function to "pretty print" the stringified data using <pre> and <code> .如果您只想将数据输出为格式化字符串,您可以创建一个函数来使用<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>

If you wanted to display the data differently (in a table, for example) you could iterate ( map ) over the keys and values returned by Object.entries to return a string of row HTML, and add that html to the page.如果您想以不同的方式显示数据(例如在表格中),您可以迭代( 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>

Addition documentation添加文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM