写出 api 对象从 fetch 到 html

Write out api object from fetch to html

我正在尝试让我的代码将 api 对象输出到 html 文件。

const container = document.createElement('div');
container.setAttribute('class', 'container');


obj = fetch('https://apis.is/concerts')
.then(function(response) {
    return response.json();
})
.then(function(data) {
    return obj = data;
})
.then(() => idk()) 

    function idk() {
    let count = 0;
        for(key in obj.results) {
            count++;
        };
        console.log(count);
        for(let i = 0; i < count; i++) {

            const card = document.createElement('div');
            card.setAttribute('class', 'card');

            const h1 = document.createElement('h1');
            h1.textContent = obj.results[i].eventDateName;

            const p = document.createElement('p');
            p.textContent = obj.results[i].dateOfShow;

            container.appendChild(card);
            card.appendChild(h1);
            card.appendChild(p);
        };
    };

我一直在尝试使用 DOM 为 html 文件创建元素,但好像有些代码被忽略了。

如果你想呈现你正在创建的所有 DOM,你必须以某种方式将它添加到浏览器显示的 DOM 树中。最简单的方法是将它添加到 body 节点。 document.querySelector('body').appendChild(container); 完成数据处理后。

但我建议稍微重构一下您的代码。例如,在此步骤中,您将结果分配给原始对象,您在其中保存承诺和结果。这也是一个全局对象,所以很快你可能会遇到竞争条件。

.then(function(data) { return obj = data; })

此外,idk() 函数与那个非常具体的变量 obj 相关联,这使得测试变得非常困难。

obj = fetch('https://apis.is/concerts')
.then(function(response) {
    return response.json(); //subscribe to response stream
})
.then((response) => {
  const allEvents = eventsDomTree(response.results); // create the events DOM tree based on response
  document.querySelector('body').appendChild(allEvents); //append the created list to document DOM tree
});

  function eventsDomTree(events) {
    const allEvents = document.createElement('div');
    events.forEach((event) => {
      const card = document.createElement('div');
      card.setAttribute('class', 'card');

      const eventName = document.createElement('h1');
      eventName.textContent = event.eventDateName;

      const dateOfShow = document.createElement('p');
      dateOfShow.textContent = event.dateOfShow

      card.appendChild(eventName);
      card.appendChild(dateOfShow);

      allEvents.appendChild(card);
    });
    return allEvents;
  }