json вывод значений по очереди

html

<!DOCTYPE html>
<html lang="ru">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <link rel="stylesheet" href="style.css">
   <script src="script.js" defer></script>
   <title>Комментарии</title>
   <div class="button">button</div>
</head>
<body>
</body>
</html>

js

const requestUrl = 'https://jsonplaceholder.typicode.com/comments';
const xhr = new XMLHttpRequest();
const method = 'GET';
function jsonCommentsLoader(method,url){
  return new Promise ((resolve,reject)=>{
    xhr.open(method,url); 
    xhr.responseType = 'json';
    xhr.onload = () => {
      if(xhr.status >= 400){
        reject(xhr.response);
      }else{
        resolve(xhr.response);
      }
    }
    xhr.onerror = () => {
      reject(xhr.response);
    }
    xhr.send();
  })
}

jsonCommentsLoader(method,requestUrl)
.then( data => {
const button = document.querySelector('.button');
function next(data,num = 0){
    for(i = num; i < num + 10; i++ ){
      console.log(data[i]);
    }
  }
  button.onlick = next(data);
})
.catch(err => console.log(err));

написал такую (простите за выражение дичь) , можно ли выводить по порядку значения, и как это сделать? Я думал сделать через замыкания, чтобы значение num всегда увеличивалось на 10 при нажатии кнопки. Но реализация меня подвела... Прощу помощи знающих как это реализовать.


Ответы (1 шт):

Автор решения: Bear Vorkuta

Попробуйте так

const requestUrl = 'https://jsonplaceholder.typicode.com/comments';
const xhr = new XMLHttpRequest();
const method = 'GET';
function jsonCommentsLoader(method,url){
  return new Promise ((resolve,reject)=>{
    xhr.open(method,url); 
    xhr.responseType = 'json';
    xhr.onload = () => {
      if(xhr.status >= 400){
        reject(xhr.response);
      }else{
        resolve(xhr.response);
      }
    }
    xhr.onerror = () => {
      reject(xhr.response);
    }
    xhr.send();
  })
}

var num = -10;
function next(data,num){
    for(i = num; i < num+10; i++ ){
      console.log(data[i]);      
    }    
  }    

jsonCommentsLoader(method,requestUrl)
.then( data => {
const button = document.querySelector('.button');
  button.onclick = () => next(data,num+=10);
})
.catch(err => console.log(err));
→ Ссылка