Увеличение JSON массив данных на один - PullRequest
0 голосов
/ 20 апреля 2020

enter image description here Мне интересно, почему это i + = 1 не увеличивает массив на 1. Когда я нажимаю на кнопку, отображается вся длина массива. Может кто-нибудь посоветовать мне, что я делаю не так. Я пытаюсь загрузить JSON данные из WP, относящиеся к сообщениям определенной категории. В этой категории, которую я загружаю (http://localhost: 8888 / wordpress / wp-json / wp / v2 / photos? Categories = 12 ), всего 2 сообщения. Когда я console.log postsData.length, я получаю значение 2. Когда я консоль журнала postsData, я получаю Object, Object Object, Object. Эти сообщения загружаются одновременно при нажатии кнопки, но я хочу, чтобы сообщения или каждый объект загружали по 1 за раз. Ниже приведен код:

var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");

if (portfolioPostsBtn){
portfolioPostsBtn.addEventListener("click", function(){
      var ourRequest = new XMLHttpRequest();
      ourRequest.open('GET', 'http://localhost:8888/wordpress/wp-json/wp/v2/photos?categories=12');
      ourRequest.onload = function() {
        if (ourRequest.status >= 200 && ourRequest.status < 400) {
          var data = JSON.parse(ourRequest.responseText);
          //console.log(data);
          createHTML(data);

        } else {
          console.log("We connected to the server, but it returned an error.");
        }
      };

      ourRequest.onerror = function() {
        console.log("Connection error");
};

ourRequest.send();

});
}

function createHTML(postsData){
  var ourHTMLString = '';
// This for loop doesn't increment by 1
  for (var i=0; i<postsData.length; i += 1){
    console.log(postsData.length);
    ourHTMLString += '<h2>' + postsData[i].title.rendered + '</h2>';
    ourHTMLString += '<img class="gallery-test" src="' +postsData[i].acf.image + '"">'
  }
  portfolioPostsContainer.innerHTML = ourHTMLString;
}

1 Ответ

1 голос
/ 20 апреля 2020

позвольте мне попытаться правильно понять ваш вопрос. если вы пытаетесь просто показать один пост за клик. вот что я думаю, вы можете попробовать:

let portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
let portfolioPostsContainer = document.getElementById("portfolio-posts-container");

// keep the payload to avoid unnecessary data requests
let postsData = [];

// using this to track click history to display the next post
let counter = 0;

/** not needed for disabling the button **/
// cycle (postsData.length) one by one starting at index 0
// for ex, if there are 3 posts, it would do 0, 1, 2, 0, 1, 2, to eons
// const incrementCounter = () => {
// counter = (counter + 1)%(postsData.length)
// };

// create post html if there is postsData
postsData.length && createHTML();

if (portfolioPostsBtn && !postsData.length){
portfolioPostsBtn.addEventListener("click", function(){
      let ourRequest = new XMLHttpRequest();
      ourRequest.open('GET', 'http://localhost:8888/wordpress/wp-json/wp/v2/photos?categories=12');
      ourRequest.onload = function() {
        if (ourRequest.status >= 200 && ourRequest.status < 400) {
          let data = JSON.parse(ourRequest.responseText);
          //console.log(data);
          postsData = data;
          createHTML();

        } else {
          console.log("We connected to the server, but it returned an error.");
        }
      };

      ourRequest.onerror = function() {
        console.log("Connection error");
};

ourRequest.send();

});
}


function disableButton () {
  // this would only work if portfolio-posts-btn is an actual button,
  // otherwise, you'll need to disable the listener and show the
  // user the btn is disabled somehow
  portfolioPostsBtn.setAttribute('disable', true);
}

function createHTML() {
  const strTemplate = `
    <h2>${postsData[counter].title.rendered}</h2>
    <img class="gallery-test" src="${postsData[counter].acf.image}">`;
  // append to the added posts
  portfolioPostsContainer.innerHTML += strTemplate;
  counter++;
  postsData.length === counter && disableButton();
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...