如何从api获取信息并将其显示在DOM上?

问题描述 投票:0回答:1

我正在尝试让 API 中的内容显示在 DOM 中。我不断收到未定义的信息,但我知道它就在那里。它显示在我的控制台中。我只是不知道当我想要的对象嵌套到另一个数组中时我还需要做哪些额外的事情,以及如何将其获取到 DOM 上。

document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('songs').addEventListener('click', getSongs)

  //getSongs()
})

function getSongs() {
  let info = document.getElementById('info')
  let songList = document.getElementById('song-list')
  //info.innerHTML = ""
  songList.innerHTML = ""
    fetch('https://itunes.apple.com/search?term=K-Pop')
      .then(resp => resp.json())
      .then(data => {
        data.results.map(song => { 
          //console.log(song)
          songList.innerHTML += `
            <li>
             <a href="#" data-name="${song.trackName}"
             data-id="${song.trackId}"> ${song.trackName} </a>
            </li>
          `
        })
        attachLinks()
    })
}

function attachLinks() {
  const songs = document.querySelectorAll('li a')
  songs.forEach(song => {
    song.addEventListener('click', displaySong)
  })
}

function displaySong(event) {
  console.log(event.target)
  let songList = document.getElementById('song-list')
  let info = document.getElementById('info')
  /*songList.innerHTML = `<h1>Song Name:</h1>
                        <p>${event.dataset.trackName}</p>
                        <h2>Artist Name:</h2>
                        <p>${event.dataset.artistName}</p>
                        <h3>Release Date:</h3>
                        <p>${event.dataset.releaseDate}</p>`*/
  songList.innerHTML = ""
  info.innerHTML = ""
  fetch(`https://itunes.apple.com/search?term=K-Pop/${event.target.dataset.id}`)
      .then(resp => resp.json())
      .then(song  => {
        //console.log(song)
          info.innerHTML += `
          <h1>${song.trackName}</h1>
          <h3>Artist Name: </h3>
          <p>${song.artistName}</p>
          <h3>Release Date: </h3>
          <p>${song.releaseDate}</p>
        `
        })
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Music</title>
        <link rel="stylesheet" href="index.css"/>
    
    </head>
        <body>
            <h1>Music</h1>
            <h2 id='input'>K-Pop</h2>
            <button id="songs">All songs</button>
            <hr>
            <br>
        <div id="main">
            <ul id="song-list">

            </ul>
        <div id="info">

        </div>
        </div>
            <script src="index.js"></script>
        </body>
</html>

这就是来自 API 的所有数据的样子:

enter image description here

javascript dom fetch-api
1个回答
1
投票

似乎第二次调用是对错误的端点进行的

尝试更改此通话

`https://itunes.apple.com/search?term=K-Pop/${event.target.dataset.id}`

为此

`https://itunes.apple.com/lookup?id=${event.target.dataset.id}`;

如果我们期望

event.target.dataset.id
为“1574770128”,则应该以这种形式返回一些 json

{
    "resultCount": 1,
    "results":
    [
        {
            "wrapperType": "track",
            "kind": "song",
            "artistId": 883131348,
            "collectionId": 1574770126,
            "trackId": 1574770128,
            "artistName": "BTS",
            "collectionName": "Permission to Dance - Single",
            "trackName": "Permission to Dance",
            "collectionCensoredName": "Permission to Dance - Single",
            "trackCensoredName": "Permission to Dance",
            "artistViewUrl": "https://music.apple.com/us/artist/bts/883131348?uo=4",
            "collectionViewUrl": "https://music.apple.com/us/album/permission-to-dance/1574770126?i=1574770128&uo=4",
            "trackViewUrl": "https://music.apple.com/us/album/permission-to-dance/1574770126?i=1574770128&uo=4",
            "previewUrl": "https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview125/v4/e1/6e/12/e16e1227-97a2-acf8-e3e0-6685f746695a/mzaf_12664711249777906736.plus.aac.p.m4a",
            "artworkUrl30": "https://is3-ssl.mzstatic.com/image/thumb/Music125/v4/cd/9b/1f/cd9b1fec-28b4-cbb9-42f5-adffcfbeba36/source/30x30bb.jpg",
            "artworkUrl60": "https://is3-ssl.mzstatic.com/image/thumb/Music125/v4/cd/9b/1f/cd9b1fec-28b4-cbb9-42f5-adffcfbeba36/source/60x60bb.jpg",
            "artworkUrl100": "https://is3-ssl.mzstatic.com/image/thumb/Music125/v4/cd/9b/1f/cd9b1fec-28b4-cbb9-42f5-adffcfbeba36/source/100x100bb.jpg",
            "collectionPrice": 0.69,
            "trackPrice": 0.69,
            "releaseDate": "2021-07-09T12:00:00Z",
            "collectionExplicitness": "notExplicit",
            "trackExplicitness": "notExplicit",
            "discCount": 1,
            "discNumber": 1,
            "trackCount": 1,
            "trackNumber": 1,
            "trackTimeMillis": 187585,
            "country": "USA",
            "currency": "USD",
            "primaryGenreName": "K-Pop",
            "isStreamable": false
        }
    ]
}

要将响应映射到视图,您需要执行以下操作:

fetch(`https://itunes.apple.com/lookup?id=${event.target.dataset.id}`)
    .then(resp => resp.json())
    .then(data  => {
        const song = data.results[0];
        if (song) {        
            info.innerHTML += `
            <h1>${song.trackName}</h1>
            <h3>Artist Name: </h3>
            <p>${song.artistName}</p>
            <h3>Release Date: </h3>
            <p>${song.releaseDate}</p>
            `;
        }
    })
© www.soinside.com 2019 - 2024. All rights reserved.