簡體   English   中英

顯示來自 JSON API 響應的帖子列表

[英]Display post list from JSON API response

我有以下 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 循環,但我不太確定如何編寫它。

您可以使用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. 首先,將 id 添加到 div。
  2. 現在添加將調用 javascript 代碼的腳本標記。 (如果您的框架處理它,我不知道您使用的是哪個框架,然后忽略此步驟)。
  3. Now use Json.parse(response) to convert to JavaScript object in your javascript file, now use filters/similar functions, and find the recent one and remaining posts.
  4. 現在使用文檔 object 通過使用您在第 1 點中創建的唯一 ID 調用您的 div,現在在那里分配/創建您 Html。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM