显示来自JSON API响应的帖子列表

时间:2020-07-02 12:21:25

标签: javascript html json

我有以下JSON

{
   "posts":[
      {
         "id":"5efb6946eab44526aecc0aaf",
         "title":"post 2Test",
         "slug":"post-2test",
         "html":"<p>Test post 2... Testing 123 testing 123</p>",
         "feature_image":null,
         "excerpt": "Test post 1"
      },
      {
         "id":"5efb6936eab44526aecc0aa9",
         "title":"Test Post",
         "slug":"test-post",
         "html":"<p>Test post one... Testing 123</p>",
         "feature_image":null,
       "excerpt": "Test post 2"
      }
   ],
   "meta":{
      "pagination":{
         "page":1,
         "limit":15,
         "pages":1,
         "total":2,
         "next":null,
         "prev":null
      }
   }
}

如何创建一个列出所有当前帖子以及添加的帖子的部分?

例如 HTML

<div class="container">
    <div class="post"> <!-- this would contain the information from the most recent post -->
       <img src={featured_img} alt="featured img">
       <h2>{title}</h2>
       <p>{excerpt}</p>
    </div>
    <div class="post"> <!-- this would contain the info of the second most recent post -->
       <img src={featured_img} alt="featured img">
       <h2>{title}</h2>
       <p>{excerpt}</p>
    </div>
</div>

我的猜测是某种for循环,但我不确定如何编写。

2 个答案:

答案 0 :(得分:3)

您可以使用for循环遍历json数据并获取特定键的值,并将生成的html分配给div

演示代码

//your response
var response = {
  "posts": [{
      "id": "5efb6946eab44526aecc0aaf",
      "title": "post 2Test",
      "slug": "post-2test",
      "html": "<p>Test post 2... Testing 123 testing 123</p>",
      "feature_image": null,
      "excerpt": "Test post 1"
    },
    {
      "id": "5efb6936eab44526aecc0aa9",
      "title": "Test Post",
      "slug": "test-post",
      "html": "<p>Test post one... Testing 123</p>",
      "feature_image": null,
      "excerpt": "Test post 2"
    }
  ],
  "meta": {
    "pagination": {
      "page": 1,
      "limit": 15,
      "pages": 1,
      "total": 2,
      "next": null,
      "prev": null
    }
  }
};

 
  var html = '';
  //looping through posts
 
  for(var i= 0 ; i<response.posts.length ;i++ ){
  //get values
   html += '<div class="post" data-value='+response.posts[i].id+'><img src='+response.posts[i].feature_image+' alt="featured img"><h2>'+response.posts[i].title+'</h2><p>'+response.posts[i].excerpt+'</p></div>';
 
  }
  //add to div
  document.getElementById("data").innerHTML= html;
<div class="container" id="data">
  <!--here data will come-->
</div>

答案 1 :(得分:0)

我们可以通过几个步骤来实现这一目标,

  1. 首先,将id添加到divs。
  2. 现在添加脚本标记,它将调用javascript代码。 (如果您的框架可以处理,我不知道您使用的是哪个框架,请忽略此步骤。)
  3. 现在使用Json.parse(response)转换为javascript文件中的JavaScript对象,现在使用过滤器/类似功能,并查找最近的帖子和剩余的帖子。
  4. 现在使用文档对象通过使用在点1处创建的唯一ID来调用div,现在在此处分配/创建HTML。

希望这会有所帮助。