繁体   English   中英

如何使用 javascript 和 HTML 显示来自 JSON 服务器的评论?

[英]How to display comments from a JSON server using javascript and HTML?

我正在制作这个网站项目,人们可以在其中发表评论,网页将动态显示评论而无需重新加载页面。 我的评论以Allcomments=[ { username: 'username', info: 'title', commentinfo: 'commentinfo ' }]格式存储在我的服务器中的数组中。 当我尝试运行我的代码Uncaught (in promise) ReferenceError: res is not defined at main.js:53 at async loadComments (main.js:50)时,我目前收到此错误,因此未显示注释。 我也对如何实现 function 感到困惑,以便它在不需要重新加载页面的情况下更新新评论。 任何帮助或提示将不胜感激:这是我的代码: index.html

<html>
<body>
<main>
  <div class="container">
    <hr>
    <h1>comments !</h1>
    <hr>
    <div class="row" id='commentsSection'></div>
  </div>
  </div>
</main>
<script src='client.js'></script>
</body>
</html>

客户端.js

async function GetComments () {
  let info = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    },
  };
  await fetch('http://127.0.0.1:8090/comments', info)
    .then((res) => { return res.json(); })
    .then(data => {
      document.getElementById('commentsSection').innerHTML;
    }).then(() => {
      const comments = JSON.stringify(res);
      for (let comment of comments) {
        const y = `
          <div class="col-4">
              <div class="card-body">
                  <h5 class= "card-title">${comment.name}</h5>
                  <h6 class="card-subtitle mb-2 text-muted">${comment.info}</h6>
                  <div>comment: ${comment.comment}</div>
                  <hr>
              </div>
          </div>
      `;
        document.getElementById('commentsSection').innerHTML =
          document.getElementById('commentsSection').innerHTML + y;
      }
    });
}

GetComments();

服务器.js


const app = express();
const port = 8090;
const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

let Allcomments=[];

app.get('/comments', (req, res) => {
    res.json(Allcomments);
});

您在.then块中使用 res ,但您没有从较早的then块中传递它:

.then((res) => { return res.json(); }) // res is defined within this block only
.then(data => {
  document.getElementById('commentsSection').innerHTML;
.then(() => {
  const comments = JSON.stringify(res); // <- ReferenceError: res is not defined

这应该解决它:

await fetch('http://127.0.0.1:8090/comment', info)

  // extract data from response body:
  .then((response) => { return response.json(); })

  // response body is comments array
  .then(comments => {
    for (let comment of comments) {
      const y = `
          <div class="col-4">
            <div class="card">
              <div class="card-body">
                  <h5 class= "card-title">${comment.name}</h5>
                  <h6 class="card-subtitle mb-2 text-muted">${comment.title}</h6>
                  <div>comment: ${comment.usercomment}</div>
                  <hr>
              </div>
             </div>
          </div>
      `;
      document.getElementById('commentsSection').innerHTML += y;
    }
  })

  // also add a catch block
  .catch(err => {
    console.error('error:', err)
  });

在您的main.js文件中,删除第一个then语句中的return关键字。 之后,将数据数组和 append 数据循环到 HTML 元素中。

async function GetComments () {
  let options = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    },
  };
  await fetch('http://127.0.0.1:3000/comment', options)
    .then(res => res.json())
    .then(data => {
      for (let comment of data) {
        const x = `
          <div class="col-4">
            <div class="card">
              <div class="card-body">
                  <h5 class= "card-title">${comment.name}</h5>
                  <h6 class="card-subtitle mb-2 text-muted">${comment.title}</h6>
                  <div>comment: ${comment.usercomment}</div>
                  <hr>
              </div>
             </div>
          </div>
      `;
        document.getElementById('commentsSection').innerHTML =
          document.getElementById('commentsSection').innerHTML + x;
      }
    });
}

GetComments();

暂无
暂无

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

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