三生石@ 2015-02-10 18:17 采纳率: 100%
浏览 133

从JSON显示图像

Trying to display the cover art with the results. Something in the img src tag is causing the app not to load. If I just point the img to data.tracks[i].album.name (obviously not a real url, but enough to test if it's working) it pastes it in just fine, but the moment I change it to paste the url in place, it makes the whole app stop working.

$('#findTracks').click(function (e) {
                e.preventDefault(); // override/don't submit form
                $('#recommendations').empty();
                var artist = $('#artist').val();
                var userid = "";
                var playlistid = "";

                $.ajax({
                    url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
                    type: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        if (data.tracks.length > 0) {
                            var tracksLength = data.tracks.length, html = '';
                            for (var i=0; i<tracksLength; i++) {
                                var href = '';
                                if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1) { // data.tracks[i].href
                                    href = data.tracks[i].href;
                                    href = 'makeReq(\''+data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+'\')';
                                    html += '<li><a href="#" onclick="' + href + '">' +data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+ ' <img src="' +data.tracks[i].album.images[0].url+ '" /></a>';html += '</li>';

                                    html += '</li>';
                                }
                            }
                            $('#third').css('display', 'block');
                            $('#recommendations').append(html);
                        } else {
                            $('#recommendations').append('<li>No matches returned.</li>');
                            $('#third').css('display', 'none');
                        }
                    },
                    error: function(err) {
                        alert("The Spotify API failed to return a response.");
                    }
                });                   
            });

This is my first time ever coding in javascript so please go easy on me! lol

EDIT:

This seems to be running well! However, many of the songs do nothing when I click on them

For example, type "Don't Stop" and only "The Black Eyed Peas - Don’t Stop The Party" works out of the first ten...anybody know why?

also, anybody known why "if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1)" is in there? If I take it out this all stops working...I am not in G.B.

  • 写回答

1条回答 默认 最新

  • weixin_33749242 2015-02-10 18:34
    关注

    If you look in the console you are getting the error

    Uncaught TypeError: Cannot read property '0' of undefined
    

    looking at the data the query returns we notice that data.tracks[i].album returns

    {
        "released": "2006",
        "href": "spotify:album:2knAf4wg8Gff8q1bXiXCTz",
        "name": "The Dutchess",
        "availability": {
            "territories": "MX"
        }
    }
    

    there is no property images so when you call

    data.tracks[i].album.images[0]
    

    you get the undefined error, causing the script to halt execution.
    I'm unfamiliar with the spootify api but taking a quick glance at the api theres the endpoint for get-album. Heres what I was able to come up with to get the album art

    $.get("http://ws.spotify.com/search/1/track.json?q=Fergie",function(data){
       var albumId = data.tracks[97].album.href.split(":")[2];
       $.get("https://api.spotify.com/v1/albums/" + albumId,function(albumResponse){
           var firstImage = albumResponse.images[0];
           $('body').append($('<img/>',{
              src : firstImage.url,
              width : firstImage.width,
              height : firstImage.height
           }));
       })
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <body></body>

    You should research more into how to get the album art since I'm unsure if this is the optimal solution.

    The search endpoint you mentioned is different from the one your using.

       One your using
       url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
       One you linked to
       url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
    

    Heres your solution with the change in endpoint

    $('#findTracks').click(function(e) {
      e.preventDefault(); // override/don't submit form
      $('#recommendations').empty();
      var artist = $('#artist').val();
      var userid = "";
      var playlistid = "";
    
      $.ajax({
        //url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
        url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
        type: 'GET',
        dataType: 'json',
        success: function(data) {
          if (data.tracks.items.length > 0) {
            data.tracks = data.tracks.items
            data.artists = data.artists.items
            var tracksLength = data.tracks.length,
              html = '';
            for (var i = 0; i < tracksLength; i++) {
              var href = '';
              href = data.tracks[i].href;
              href = 'makeReq(\'' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + '\')';
              html += '<li><a href="#" onclick="' + href + '">' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + ' <img src="' + data.tracks[i].album.images[0].url + '" /></a>';
              html += '</li>';
              html += '</li>';
    
            }
            $('#third').css('display', 'block');
            $('#recommendations').append(html);
          } else {
            $('#recommendations').append('<li>No matches returned.</li>');
            $('#third').css('display', 'none');
          }
        },
        error: function(err) {
          alert("The Spotify API failed to return a response.");
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    Artist:
    <input type="text" id="artist" />
    <button id="findTracks">Find Tracks</button>
    <div id="recommendations"></div>

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用