将结果从fetchapi输出到html

时间:2018-10-20 11:07:28

标签: javascript html fetch

我有这段代码可以返回在线广播中当前播放的歌曲。我无法将结果输出到html。当我控制台记录结果时,如下所示,我会得到3条结果。但是,当我在html上显示该内容时,我只会得到一个结果。我的问题是我应该如何浏览结果并将其输出到页面上

    function getSongs(){
let url = "http://socket.radionula.com/playlist" ;
let API_KEY = '';
let songCount = 1;
let watchVideoURL = 'https://www.youtube.com/watch?v=';
        fetch(url)
        .then(res => res.json())
        .then(data => {
            Object.keys(data).forEach(function(key){
                let songtitle =  data[key].currentSong.title
                let songartist = data[key].currentSong.artist
                console.log(`Currently on ${key} :${songartist}-${songtitle} `)
                fetch(`https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=${songCount}&q=${songartist}+${songtitle}&key=${API_KEY}`)
                .then(result => result.json())
                .then(ytdata => {   
                    let ytID = ytdata.items[0].id.videoId;
                    console.log(`YouTube url =  ${watchVideoURL}${ytID}`)
                })
                .catch(err =>{console.log('There was an error')})
            }) 
        });   

    }
getSongs();

2 个答案:

答案 0 :(得分:0)

您的getSongs()应该返回一个数组,然后您可以:

const parent = document.querySelector('.parent')
getSongs().map(el => parent.appendChild(`<p>${el}</p>`))

答案 1 :(得分:0)

ytdata.items似乎是一个数组。因此,考虑到这一点,您将需要一个循环结构来遍历结果并获取每首歌曲。像这样:

.then(ytdata => {

  // Our array of songs
  const songs = ytdata.items

  // The target container in the HTML (this needs to exist beforehand)
  const songContainer = document.getElementById('songs-container')

  // Iterate over each song in the array
  for (let song of songs) {

    // Create an empty link (anchor) element
    let songLink = document.createElement('a')

    // Fill in the href with a valid URL
    songLink.href = watchVideoURL + song.id.videoId

    // Populate the visible text for the link
    songLink.innerText = `${songtitle} by ${songartist}`

    // Place it inside the target DOM element
    songContainer.append(songLink)
  }

})

注意append is experimental technology,但可以在任何现代浏览器上使用。如果您希望确保与旧版浏览器完全兼容,请使用更强大且经过验证的方法,例如insertAdjacentHTML。像这样: songContainer.insertAdjancentHTML('beforeend', songLink)