javascript - 我不知道如何使用更新的 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
解决方案
通过 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 调用结果的上下文,我希望这对您有用
推荐阅读
- javascript - 模拟文件拖入浏览器的拖动事件
- testing - 在 testcafe 上选择 chrome 作为浏览器并在测试更改中间模拟设备以更改为设备视图
- laravel - 如何在没有昂贵电话的情况下在频道中获得最新回复?
- entity-framework - 实体框架单向关系.Net Core 3.1
- ruby-on-rails - Cequel 和 Ruby3/Rails 6 的 ArgumentError
- javascript - XMLHttpRequest 不适用于特定 URL?
- python - 通过嵌套列表搜索,找到子元素并根据值删除
- css - 反应中的CSS冲突
- javascript - Check if an array is stack-sortable
- java - 澄清:不同模态设备的应用程序颜色变化,但在 android studio 中使用相同的颜色代码