F
F
furcifer2018-06-10 15:37:31
JavaScript
furcifer, 2018-06-10 15:37:31

API not displaying data?

Hello! Please help me figure it out. You need to create a js application, the data is taken from the api, and should be displayed on the web page. There are no errors in the console, but nothing is displayed. With api, the data comes through, I checked it through console.log. What did you write wrong and where could be the error?

const wrap = document.createElement('div');
wrap.setAttribute('class', 'sw-wrap');
const list = document.createElement('div');
list.setAttribute('class', 'sw-list');

wrap.appendChild(list);


////////////////////////////////////////////
var swapi = new XMLHttpRequest();
swapi.open("GET", "http://swapi.co/api/films/", true);

swapi.onload=function(){
  var data=JSON.parse(this.response);
  
  data.results.forEach( film => {
    console.log(film.title);
    const wrap = document.createElement('div');
    wrap.setAttribute('class', 'sw-wrap');
    const list = document.createElement('div');
    list.setAttribute('class', 'sw-list');

    const item = document.createElement('div');
    item.setAttribute('class', 'sw-item');
    const info = document.createElement('div');
    info.setAttribute('class', 'sw-item__info');
    const description = document.createElement('div');
    description.setAttribute('class', 'opening_crawl');
    
    const title = document.createElement('h3');
    title.textContent=film.title;
    const episode = document.createElement('h3');
    episode.textContent=film.episode_id;
    const director = document.createElement('div');
    director.textContent=film.director;
    const release = document.createElement('div');
    release.textContent=film.release_date;
    
    list.appendChild(item);
    item.appendChild(info);
    item.appendChild(description);
    info.appendChild(title);
    info.appendChild(episode);
    info.appendChild(director);
    info.appendChild(release);
  });
}
swapi.send();

The markup should look like this.
<div class="sw-wrap">
      <div class="sw-list">
        <div class="sw-item">
          <div class="sw-item__info">
            <h3 class="title">A New Hope</h3>
            <h3 class="episode_id">4</h3>
            <div class="director">George Lucas</div>
            <div class="producer">Gary Kurtz, Rick McCallum</div>
            <div class="release_date">1977-05-25</div>
          </div>
          <div class="opening_crawl">.</div>
        </div>
      </div>
      
    </div>

Thanks in advance for your replies

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Proskurin, 2018-06-10
@furcifer

You don't add created elements anywhere. You re-create wrap and list and don't add them anywhere. Try like this

const wrap = document.createElement('div');
wrap.setAttribute('class', 'sw-wrap');
const list = document.createElement('div');
list.setAttribute('class', 'sw-list');

wrap.appendChild(list);


////////////////////////////////////////////
var swapi = new XMLHttpRequest();
swapi.open("GET", "http://swapi.co/api/films/", true);

swapi.onload=function(){
  var data=JSON.parse(this.response);
  
  data.results.forEach( film => {
    console.log(film.title);
   
    const item = document.createElement('div');
    item.setAttribute('class', 'sw-item');
    const info = document.createElement('div');
    info.setAttribute('class', 'sw-item__info');
    const description = document.createElement('div');
    description.setAttribute('class', 'opening_crawl');
    
    const title = document.createElement('h3');
    title.textContent=film.title;
    const episode = document.createElement('h3');
    episode.textContent=film.episode_id;
    const director = document.createElement('div');
    director.textContent=film.director;
    const release = document.createElement('div');
    release.textContent=film.release_date;
    
    list.appendChild(item);
    item.appendChild(info);
    item.appendChild(description);
    info.appendChild(title);
    info.appendChild(episode);
    info.appendChild(director);
    info.appendChild(release);
  });
}
swapi.send();

UPD: Plus you haven't added wrap to the page yet. To do this, create a block in html, for example,
and add wrap to it
document.getElementById('content').appendChild(wrap);

I
Ihor Bratukh, 2018-06-10
@BRAGA96

In such tasks, I would recommend you to separate logic and output.
Just a few lines of logic and you get a clean template for displaying data on the page.

(function() {
    'use strict';

    // Инициализируем объект методов swapi
    const swapi = {
        // Метод инициализации, принимает массив объектов данных из API и объект настроек
        init(response, setting) {
            // Зададим основной контейнер куда будут вставлятся данные
            // Можно явно указать в свойстве container или создать и вернуть в свойстве create()
            const element = setting.container || setting.create()
            // Выводим данные на страницу
            appendCollectionOutput(element, filterArray(response, (data, index) => {
                return parseHtml(setting.items(data, index))
            }))
        }
    }

    // Инициализация запроса к API
    ajax({
        url: 'https://swapi.co/api/films/',
        method: 'GET',
        contentType: 'application/json; charset=UTF-8',
        success(response) {
            // Инициализируем плагин, передаем данные из API и пишем объект настроек
            swapi.init(JSON.parse(response).results, {
                // Определяем куда будет вставлятся html из функции items(data)
                container: document.querySelector('.swapi-container'),
                // Определяем шаблон вывода
                items(data) {
                    return `
                        <div class="sw-wrap">
                            <div class="sw-list">
                                <div class="sw-item">
                                    <div class="sw-item__info">
                                        <h3 class="title">${data.title}</h3>
                                        <h3 class="episode_id">${data.episode_id}</h3>
                                        <div class="director">${data.director}</div>
                                        <div class="producer">${data.producer}</div>
                                        <div class="release_date">${data.release_date}</div>
                                    </div>
                                    <div class="opening_crawl">.</div>
                                </div>
                            </div>
                        </div>
                    `
                }
            })
        }
    })

    /**
      * Вставка HTMLCollection на страницу
      * @param {Node} element - Node элемент, куда будет вставлятся коллекция
      * @param {HTMLCollection} collection - масив HTMLCollection
    **/
    function appendCollectionOutput(element, collection) {
        for (let i = 0; i < collection.length; i++) {
            element.appendChild(collection[i][0])
        }
    }

    /**
      * Парсинг HTML из строки
      * @param {string} string - html строка
      * @returns {HTMLCollection} - html коллекция node узлов
    **/
    function parseHtml(string) {
        const template = document.implementation.createHTMLDocument();
        template.body.innerHTML = string;
        return template.body.children;
    }

    /**
      * Фильтр и перебор по массиву
      * @param {array} data - массив данных
      * @param {function} filter - функция для фильтрации
      * @returns {array} - отфильтрованный массив данных
    **/
    function filterArray(data, filter) {
        const array = [];
        for (let i = 0; i < data.length; i++) {
            array.push(filter(data[i], i));
        }
        return array;
    }

    /**
      * XMLHttpRequest
      * @param {object} params - параметры запроса
      * url (string), method (string), contentType (string), data (any), async (boolean), success (function), error (function)
    **/
    function ajax(params) {
        var request = new XMLHttpRequest();
        request.open(params.method || 'GET', params.url || window.location.href, params.async || true);
        request.setRequestHeader('Content-Type', params.contentType || 'application/x-www-form-urlencoded; charset=UTF-8');
        request.onreadystatechange = function() {
            if (this.readyState === 4) {
                if (this.status >= 200 && this.status < 400) {
                    if (params.success) params.success(this.response, this.statusText, this.status);
                } else {
                    if (params.error) params.error(this);
                }
            }
        };
        request.send(params.data ? JSON.stringify(params.data) : '');
        request = null;
    }

})()

In the initialization object, you can specify where to insert html from the items() function.
Or specify an already created element:
Or create and return:
create() {
  document.body.insertAdjacentHTML('afterBegin', function() {
    return '<div class="swapi-container"></div>'
  }())
  return document.querySelector('.swapi-container')
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question