【问题标题】:How to display the last four blog posts using JSON API in div tag如何在 div 标签中使用 JSON API 显示最后四篇博客文章
【发布时间】:2019-07-22 05:14:22
【问题描述】:

如何在 HTML 中显示最新的四篇博客文章 WordPress API

HTML:

<div id="content" class="content"></div>

JavaScript:

<script>
  $(document).ready(function() {
    $.getJSON("https://startupet.com/blog/wp-json/wp/v2/posts", function(data) {
      console.log(data);
    });  
  })
</script>

我正在获取图片帖子和标题

JSON 文件:https://startupet.com/blog/wp-json/wp/v2/posts

【问题讨论】:

  • 你为此做了什么?
  • 在前端使用数据表或在后端修改查询作为分页
  • @RinkeshGolwala我几乎不知道该怎么办

标签: javascript jquery json wordpress api


【解决方案1】:

您可以使用带有负数的slice 来获取数组末尾的元素。

在本例中,dummy api 返回一个响应,slice(-4) 用于获取最后 4 个元素,然后迭代该数组并创建 dom

$.getJSON("https://jsonplaceholder.typicode.com/posts", function(data) {
  let string = '';
  data.slice(-4).forEach(function(item) {
    string += `<div>${item.title}</div>`
  })
  $("#content").append(string)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" class="content">
</div>

【讨论】:

  • 我无法访问发布的照片​​。我看不到照片的路径。请帮忙
【解决方案2】:

您可以根据时间戳对数组进行排序,并根据您需要的项目数对其进行切片。

接下来是遍历结果并在 html 中显示您想要的任何内容

$(document).ready(function(){
$.getJSON( "https://startupet.com/blog/wp-json/wp/v2/posts", 
function(data) {
const result = data.sort((a,b) => (a.date > b.date)).slice(Math.max(data.length - 4, 1)); 
console.log(result); // Your Result contains the last 4 posts sorted by date
});  
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" class="content">
</div>

【讨论】:

  • 我无法访问发布的照片​​。我看不到照片的路径。请帮忙
  • 它是否存在于 json 响应中?
  • 我不知道。我找不到
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多