侧边栏壁纸
博主头像
前端学习

行动起来,活在当下

  • 累计撰写 307 篇文章
  • 累计创建 18 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

ajax连接网易云音乐api接口,并实现在页面展示搜索结果与试听

Administrator
2022-05-19 / 0 评论 / 0 点赞 / 131 阅读 / 0 字

因为网易云音乐搜索与听歌是两个接口,所以需要用到两次ajax,并且听歌接口需要在搜索接口请求成功以后再触发;

搜索音乐:<input type="text" id="search"> <input type="button" value="搜索" id="btn">
<ul id="list">
  <li></li>&emsp;&emsp;<a href=""></a><br>
  <li></li>&emsp;&emsp;<a href=""></a><br>
  <li></li>&emsp;&emsp;<a href=""></a><br>
  <li></li>&emsp;&emsp;<a href=""></a><br>
  <li></li>&emsp;&emsp;<a href=""></a><br>
  <li></li>&emsp;&emsp;<a href=""></a><br>
  <li></li>&emsp;&emsp;<a href=""></a><br>
  <li></li>&emsp;&emsp;<a href=""></a><br>
  <li></li>&emsp;&emsp;<a href=""></a><br>
  <li></li>&emsp;&emsp;<a href=""></a><br>
</ul> 
<button id="lis">下一页</button>

JavaScript

$(function () {
  $('#btn').click(function () {
    $search = $('#search').val();
    console.log($search);
    var api = 'http://music.eleuu.com/search?keywords=' + $search + '';
    console.log(api);
    $.ajax({
      type: 'get',
      url: api,
      dataType: 'json',
      success: function (result) {
        $res = result.result.songs;
        console.log($res);
        $.each($res, function (index, value) {
          console.log(index);
          console.log(value);
          $('#list li').eq(index).html(value.name);
          $('#list a').eq(index).html('试听一下').attr('name', value.id);
        });
        $.ajax({
          type: 'get',
          url: 'http://music.eleuu.com/song/url?id=' + $('#list a').attr('name') + '',
          dataType: 'json',
          success: function (res) {
            var listen = res.data;
            $.each(listen, function (index, value) {
              console.log(value.url);
              console.log($('#list a').attr(''));
              $('#list a').attr('href', value.url)
            })
          }
        })
      }
    })
  })
})

先获取用户在输入框输入的内容,然后将内容传入api接口,当用户点击搜索按钮时就能获取到结果,并将搜索歌曲id储存为a标签的name里面;在搜索成功后再建立一个ajax接口,将a标签name属性的数据获取赋予听歌接口,然后再获取该接口数据中的url接口,以实现用户点击试听就可以获取到对应歌曲的播放链接。

0

评论区