You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据另一JSON的ID过滤JSON文件?博客评论匹配问题

问题描述

我有一个博客的文章详情页(第二页),通过首页的链接跳转过来,用URLSearchParams获取URL里的文章ID。现在要从接口获取文章数据,同时获取对应文章的评论(总共有100篇文章、500条评论),但尝试过滤对应文章的评论没成功,怀疑是两个AJAX请求的作用域问题,以下是我的代码:

$(function () {
 
  $.ajax({
    type: "GET",
    url: "https://jsonplaceholder.typicode.com/posts",
    dataType: 'json',
    success: function (result) {
      var params = new window.URLSearchParams(window.location.search);//获取文章ID
      var postId = params.get('post');
      var postObj = result.filter(function (postElm) {
        return postId == postElm.id; //对比两个ID

      });

      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>`
          );
        });
      });

    }

  });


});
解决方案

你的问题核心不是作用域问题,而是评论过滤逻辑错误,还有几处细节问题:

  • 过滤逻辑错误:你注释的代码里用comElm.id == postElm.id完全不对,评论的postId才对应文章的id,而且postElm在评论请求的回调里无法访问,但你已经拿到了postId变量,直接用它过滤即可。
  • 没必要请求全部评论:接口支持按postId筛选评论,直接请求https://jsonplaceholder.typicode.com/comments?postId=${postId},就能拿到对应文章的评论,不用拉取500条再过滤,更高效。
  • HTML语法错误:原代码里<a post=" + post.id + "'>少了一个双引号,caard-body是拼写错误,应该是card-body。

修正后的代码如下:

$(function () {
  $.ajax({
    type: "GET",
    url: "https://jsonplaceholder.typicode.com/posts",
    dataType: 'json',
    success: 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('文章不存在');
        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?postId=${postId}`, function (comments) {
        comments.forEach(comment => {
          $("#comm").append(
            `<div class='card bg-secondary text-white'>
              postId: ${comment.postId}
              <h6 class="card-header">ID: ${comment.id}</h6>
              <div class="card-body">Name: ${comment.name}
                <p class="email">Email: ${comment.email}</p>
                <p class="form-control comment-text text-white">Body: ${comment.body}</p>
              </div>
            </div>`
          );
        });
      });
    }
  });
});

关键修改说明

  1. 评论请求改为带postId参数的接口,直接获取目标评论,减少数据传输
  2. 修正HTML拼接中的引号缺失和类名拼写错误
  3. 简化评论渲染逻辑,因为返回的已经是对应文章的评论,无需额外过滤

内容的提问来源于stack exchange,提问作者new brain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 04:54:56