提问人:new brain 提问时间:3/6/2023 最后编辑:76484new brain 更新时间:3/11/2023 访问量:70
如何过滤一个 json 文件以匹配另一个 json 的 id?
How do I filter a json file to match with another json's id?
问:
我有一个博客,这是第二页,你可以从第一页找到链接。这就是我使用 .现在,从第一个 JSON 开始,我得到了帖子。对于每个帖子,您可以通过 ID 获得许多评论。我必须为每个帖子显示已经存在的评论。有 100 个帖子和 500 条评论。这是我的代码:URLSearchParams
$(function () {
$.ajax({
type: "GET",
url: "https://jsonplaceholder.typicode.com/posts",
dataType: 'json',
success: function (result) {
var params = new window.URLSearchParams(window.location.search);//getting the post ID
var postId = params.get('post');
var postObj = result.filter(function (postElm) {
return postId == postElm.id; //comparing the 2 IDs
});
if (postObj.length < 1) {
alert('post not found');
return;
}
renderPage(postObj[0]);
function renderPage(post) {
$("#loop").append(
"<div class='card bg-success text-white'>User ID:" + post.userId +
"<div class='card-header'>ID:" + post.id + "</div>" +
"<div class='card-body'>" +
"<a post=" + post.id + "'><h5 class='card-title'>" + post.title + "</h5></a>" +
"<p class='card-text'>" + post.body + "</p>" + "</div>" +
"</div>");
}
$.getJSON('https://jsonplaceholder.typicode.com/comments', function (data) {
data.forEach(comments => {
// var comObj = data.filter(function (comElm) {
// return comElm.id == postElm.id;
// });
$("#comm").append(
`<div class='card bg-secondary text-white'>
postId: ${comments.postId}
<h6 class="card-header ">ID: ${comments.id}
<div class="caard-body">Name: ${comments.name}
<p class="email">Email: ${comments.email}</p>
<p class="form-control comment-text text-white">Body: ${comments.body}</p>
</div>`
);
});
});
}
});
});
我试图过滤它们,但它不起作用,因为我猜它们不在同一个 AJAX 中。
答:
0赞
new brain
3/6/2023
#1
我做到了,这是我的代码:
$(function() {
$.getJSON('https://jsonplaceholder.typicode.com/posts', function(result) {
var params = new window.URLSearchParams(window.location.search);
var postId = params.get('post');
var postObj = result.filter(function(postElm) {
return postId == postElm.id;
});
if (postObj.length < 1) {
alert('post not found');
return;
}
console.log(postId);
getsComments(postId);
renderPage(postObj[0]);
function getsComments(postId) {
$.getJSON('https://jsonplaceholder.typicode.com/comments', function(data) {
var commments = data.filter(function(comElm) {
return comElm.postId == postId;
});
commments.forEach(comments => {
$("#comm").append(`<div class='card bg-secondary text-white'>
postId: ${comments.postId}
<h6 class="card-header ">ID: ${comments.id}
<div class="caard-body">Name: ${comments.name}
<p class="email">Email: ${comments.email}</p>
<p class="form-control comment-text text-white">Body: ${comments.body}</p>
</div>`);
});
});
}
function renderPage(post) {
$("#loop").append("<div class='card bg-success text-white'>User ID:" + post.userId + "<div class='card-header'>ID:" + post.id + "</div>" + "<div class='card-body'>" + "<a post=" + post.id + "'><h5 class='card-title'>" + post.title + "</h5></a>" + "<p class='card-text'>" + post.body + "</p>" + "</div>" + "</div>");
}
});
});
评论