简体   繁体   English

使用 Javascript 获取并显示 API 信息

[英]Fetch and display API information using Javascript

 fetch("https://wptavern.com/wp-json/wp/v2/posts").then((response) => { if (response.ok) { return response.json(); } else { throw new Error(.NETWORK RESPONSE ERROR"); } }).then((data) => { console.log(data); displayDetails(data); }).catch((error) => console.error("FETCH ERROR:", error)); //*function displayDetails(data) { const informations = data[0]; //create a variable and store the array you need to access const informationsDiv = document.getElementById("informations"); //create a vaiable with a div to display the data const informationsTitle = informations.title.rendered; //create a variable and access the specific data, title in this case const heading = document.createElement("h1"); //create a heading variable h1 heading.innerHTML = informationsTitle; informationsDiv.appendChild(heading); const informationsImage = document.createElement("img"); //create a variable for the image informationsImage.src = informations.episode_featured_image; //specify the image source inside the array informationsDiv.appendChild(informationsImage); const informationsDate = informations.date; //create a variable and access the date const heading1 = document.createElement("p"); //create a variable to use in the DOM heading1.innerHTML = informationsDate; informationsDiv.appendChild(heading1); //append the data //} function displayDetails(data) { let informationsDiv = document.getElementById("informations"); for(var i = 0; i < data.length; i++) { let informations = data[i]; let informationsTitle = informations.title.rendered; let heading = document.createElement("h1"); heading.innerHTML = informationsTitle; informationsDiv.appendChild(heading); let informationsImage = document.createElement("img"); informationsImage.src = informations.episode_featured_image; informationsDiv.appendChild(informationsImage); let informationsDate = informations.date; let heading1 = document.createElement("p"); heading1.innerHTML = informationsDate; informationsDiv.appendChild(heading1); } }
 .swiper { margin: auto; padding: auto; width:100%; height: 100%; }.swiper-slide { text-align: center; font-size-adjust: 15px; background: #fff; /* Center slide text vertically */ display: -webkit-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; -webkit-justify-content: center; justify-content: center; -webkit-box-align: center; -ms-flex-align: center; -webkit-align-items: center; align-items: center; background-color: #c2bdd1; }.swiper-slide img { display: block; width: 100%; height: 100%; object-fit: cover; } html,body { height:100%; background: #eee; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; font-size: 14px; color: #000; margin: auto; padding: 0; } #informations{ max-width: 700px; text-align: center; padding: 30px 30px 12px 30px; color: rgb(252, 252, 252); background-color: #7766d7; border: 4px solid #9387f2; border-radius: 5px; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <title>Document</title> </head> <body> <link rel="stylesheet" href="https.//cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.css" /> <link rel="stylesheet" href="style.css" /> <:--Script--> <script src="script/script.js"></script> <.-- Swiper --> <div class="swiper mySwiper"> <div class="swiper-wrapper "> <div class="swiper-slide"> <div id="informations"></div> </div> <div class="swiper-slide">Slide 2</div> <div class="swiper-slide">Slide 3</div> <div class="swiper-slide">Slide 4</div> <div class="swiper-slide">Slide 5</div> <div class="swiper-slide">Slide 6</div> <div class="swiper-slide">Slide 7</div> <div class="swiper-slide">Slide 8</div> <div class="swiper-slide">Slide 9</div> </div> <div class="swiper-button-next"></div> <div class="swiper-button-prev"></div> </div> <.-- Swiper JS --> <script src="https.//cdn,jsdelivr.net/npm/swiper/swiper-bundle:min,js"></script> <:-- Initialize Swiper --> <script> var swiper = new Swiper(":mySwiper". { allowTouchMove, true: navigation. { nextEl, ",swiper-button-next": prevEl: ",swiper-button-prev"; }, keyboard: { enabled: true, } }); </script> </body> </html>

I am building a carousel where on every page I want to display information (title, image, date) taken from this API: https://wptavern.com/wp-json/wp/v2/posts我正在构建一个轮播,我想在每个页面上显示取自此 API 的信息(标题、图像、日期): https://wptavern.com/wp-json/wp/v2/posts

So far I managed to write this script:到目前为止,我设法编写了这个脚本:

fetch("https://wptavern.com/wp-json/wp/v2/posts")
  .then((response) => {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error("NETWORK RESPONSE ERROR");
    }
  }).then((data) => {
    console.log(data);
    displayDetails(data);
  }).catch((error) => console.error("FETCH ERROR:", error));

function displayDetails(data) {
  const informations = data[0];
  const informationsDiv = document.getElementById("informations");
  const informationsTitle = informations.title.rendered;
  const heading = document.createElement("h1");
  heading.innerHTML = informationsTitle;
  informationsDiv.appendChild(heading);
  const informationsImage = document.createElement("img");
  informationsImage.src = informations.episode_featured_image;
  informationsDiv.appendChild(informationsImage);
  const informationsDate = informations.date;
  const heading1 = document.createElement("p");
  heading1.innerHTML = informationsDate;
  informationsDiv.appendChild(heading1);
}

The problem is, this works only on the first slide.问题是,这仅适用于第一张幻灯片。 If I try to call the same function for slide n2 and change all the variables and the start of the array, from data[0] to data[1], then slide n1 doesn't showcase info anymore, but slide n2 does!如果我尝试为幻灯片 n2 调用相同的 function 并更改所有变量和数组的开头,从数据 [0] 到数据 [1],则幻灯片 n1 不再显示信息,但幻灯片 n2 会!

I also added a picture of HTM because I don't know how to format code properly and stack overflow is not allowing me to post the question.我还添加了一张 HTM 图片,因为我不知道如何正确格式化代码,而且堆栈溢出不允许我发布问题。

The end result should display all the recent articles provided by the API.最终结果应该显示 API 提供的所有近期文章。

Thank you for your time.感谢您的时间。

I've updated your code, this should work:我已经更新了你的代码,这应该可以工作:

 fetch("https://wptavern.com/wp-json/wp/v2/posts").then((response) => { if (response.ok) { return response.json(); } else { throw new Error(.NETWORK RESPONSE ERROR"); } }).then((data) => { console.log(data); displayDetails(data); }).catch((error) => console.error("FETCH ERROR:", error)); function displayDetails(data) { let informationsDiv = document.getElementById("slider"); for(var i = 0; i < data.length; i++) { var slide = document.createElement("div"); slide.className = "swiper-slide"; var slideContent = document.createElement("div"); slideContent.className = "informations"; let informations = data[i]; let informationsTitle = informations.title.rendered; let heading = document.createElement("h1"); heading.innerHTML = informationsTitle; slideContent.appendChild(heading); let informationsImage = document.createElement("img"); informationsImage.src = informations.episode_featured_image; slideContent.appendChild(informationsImage); let informationsDate = informations.date; let heading1 = document.createElement("p"); heading1.innerHTML = informationsDate; slideContent.appendChild(heading1); slide.appendChild(slideContent); informationsDiv.appendChild(slide); } }
 .swiper { margin: auto; padding: auto; width:100%; height: 100%; }.swiper-slide { text-align: center; font-size-adjust: 15px; background: #fff; /* Center slide text vertically */ display: -webkit-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; -webkit-justify-content: center; justify-content: center; -webkit-box-align: center; -ms-flex-align: center; -webkit-align-items: center; align-items: center; background-color: #c2bdd1; }.swiper-slide img { display: block; width: 100%; height: 100%; object-fit: cover; } html,body { height:100%; background: #eee; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; font-size: 14px; color: #000; margin: auto; padding: 0; }.informations{ max-width: 700px; text-align: center; padding: 30px 30px 12px 30px; color: rgb(252, 252, 252); background-color: #7766d7; border: 4px solid #9387f2; border-radius: 5px; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <title>Document</title> </head> <body> <link rel="stylesheet" href="https.//cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.css" /> <link rel="stylesheet" href="style.css" /> <:--Script--> <script src="script/script.js"></script> <.-- Swiper --> <div class="swiper mySwiper"> <div class="swiper-wrapper" id="slider"> </div> <div class="swiper-button-next"></div> <div class="swiper-button-prev"></div> </div> <.-- Swiper JS --> <script src="https.//cdn,jsdelivr.net/npm/swiper/swiper-bundle:min,js"></script> <:-- Initialize Swiper --> <script> var swiper = new Swiper(":mySwiper". { allowTouchMove, true: navigation. { nextEl, ",swiper-button-next": prevEl: ",swiper-button-prev"; }, keyboard: { enabled: true, } }); </script> </body> </html>

It basically creates a new swiper-slide for each result of the API, and appends it to your slider.它基本上为swiper-slide每个结果创建一个新的滑动滑动,并将其附加到您的 slider。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 JavaScript 中使用提取(并显示)调用一个更复杂的数组 API? - How to call an API that is a more complex array, in JavaScript using fetch (and display it)? 当提供 imageLink 时,使用 fetch api 显示图像 - javascript - display an image using fetch api when imageLink is provided - javascript 使用 Fetch 从后端 API 收集信息? - Using Fetch to gather information from a Backend API? 如何使用 HTML 表在 HTML 表上显示所有 JSON 获取 API 内容 - How to display all JSON Fetch API content on a HTML table using JavaScript 使用纯 javascript 和引导程序:如何显示模式对话框确认来自 JSON API 的提取操作的响应 - Using pure javascript and Bootstrap : How to display a modal dialog confirm response from fetch operation from JSON API 如何使用 JavaScript 显示用户输入的信息? - How to display user entered information using JavaScript? 无法使用 fetch API 动态显示数据 - unable to display data dynamically using fetch API Javascript 使用 POST 获取 gif 并显示 - Javascript fetch gif using POST and display 如何使用 Dailymotion API 获取标题、缩略图、描述信息? - How to fetch Title,Thumbnail, Description information using Dailymotion API? 使用带有 SOAP 网络服务的 javascript fetch API - using javascript fetch API with a SOAP web service
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM