首页 > 解决方案 > 我不知道如何使用更新的 json 数据呈现新页面

问题描述

我不确定我的错误在哪里。我是节点新手,我一直在学习。这个过程有点匆忙,因为它是暑期班,所以节奏很快。我知道我的路线/控制器很奇怪,这不是最好的格式。我计划在截止日期后稍后“修复”这个项目。

我需要从 AJAX 获取结果并放入我的 post.ejs 文件中。当用户单击我的 index.ejs 中的标题时,我希望它使用正确的 post.title 和 post.content 将它们重定向到我的 post.ejs 文件

这是我onclick要调用的函数的Ajax

$("#thisTitle").on("click", function (e) {
  e.preventDefault();
  var post = $(this).text();

  $.ajax({
    type: "GET",
    url: "/post/" + post,
    dataType: "json",
    success: function (data) {
      location.assign("/post");
    },
  });
});

这是我的 index.ejs 文件

<div class="row">
  <div class="column">
    <div id="containerBlogPost">
      <div class="blogPost">
        <a href="">
          <h3 class="resize" id="thisTitle"><%= posts[0].title %></h3>
        </a>
        <p class="resize">
          "<%= posts[0].content %>"
        </p>
      </div>
    </div>
  </div>
</div>

最后,这是我的 GET 请求

app.get("/post/:item", async (req, res) => {
  try {
    const post = await Post.findOne({ title: req.params.item });
    res.json({
      title: post.title,
      content: post.content,
    });
  } catch (err) {
    res.json({ message: err });
  }
});

app.get("/post", function (req, res) {
  Post.find({}, function (err, data) {
    if (err) throw err;
    res.render("post", { posts: data });
  });
});

这是我试图访问动态 json 数据的 post.ejs

<!DOCTYPE html>
<html>
  <body>
    <%- include('partials/header'); -%>

    <div class="post-page">
      <div class="postContainer">
        <div class="postTitle">
          <h3 id="singlePostTitle"><%= test %></h3>
        </div>

        <div class="blogPostPage" id="singlePostContent"><%= test %>"</div>
      </div>
    </div>
  </body>
</html>

当我在邮递员上访问我的 GET 请求/post/:item时,我得到了我想要获取的结果。我只是不知道如何使用该json数据并将其正确传递到 ajax 以呈现具有动态数据的 /post 页面/post/:item

标签: javascriptnode.jsajax

解决方案


通过 ajax 调用,您可以获得JSON与您正在查找的帖子的数据相对应的数据,并且在本例 index.ejs 中,它应该在同一文档中使用其数据。当在$ajax回调中实现 JSON 时success,您重定向到另一个文档并且 JSON 保持未使用状态。也许您应该重新考虑您想要做什么,例如,您可以在同一视图中显示在 ajax 中获得的帖子index.ejs,例如

添加index.ejs带有类输出的 div

<div class="blogPost">
  <div class="output"></div> <!-- add this element -->
  <a href="">
    <h3 class="resize" id="thisTitle"><%= posts[0].title %></h3>
  </a>
  <p class="resize">
    "<%= posts[0].content %>"
  </p>
</div>

在 JavaScript 中

$("#thisTitle").on("click", function (e) {
  e.preventDefault();
  var post = $(this).text();

  $.ajax({
    type: "GET",
    url: "/post/" + post,
    dataType: "json",
    success: function (data) {
      document.querySelector(".output").innerHTML = JSON.stringify(data);

      // location.assign("/post");
    },
  });
});

相关的是您了解应该使用 ajax 调用结果的上下文,我希望这对您有用


推荐阅读