http.js

  1. var baseUrl = "http://192.168.4.18:3000/"
  2. function ajax({
  3. url,
  4. method="get",
  5. success
  6. }){
  7. var xhr = new XMLHttpRequest()
  8. xhr.open(method,url=baseUrl+url,true)
  9. xhr.send()
  10. xhr.onreadystatechange = function(){
  11. if(xhr.readyState == 4 && xhr.status == 200){
  12. var res = JSON.parse(xhr.responseText)
  13. success(res)
  14. }
  15. }
  16. }
  17. function httpAlbum(callback){
  18. ajax({
  19. url:"top/album",
  20. success:res =>{
  21. callback(res)
  22. }
  23. })
  24. }
  25. function handleData(res){
  26. var arr = res.albums.slice(0,3)
  27. // console.log(arr);
  28. arr.forEach(item =>{
  29. var template = `
  30. <div class="container">
  31. <img src=${item.blurPicUrl} alt="">
  32. <p class="title">${item.name}</p>
  33. <p class="name">${item.artist.name}</p>
  34. </div>
  35. `
  36. $("#app").append(template)
  37. })
  38. }

index.js

  1. httpAlbum(handleData) // 调用

网易云

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <script src="js/http.js"></script>
  8. <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
  9. <script src="index.js"></script>
  10. <style>
  11. *{
  12. margin: 0;
  13. padding: 0;
  14. }
  15. #app{
  16. width: 700px;
  17. margin: 0 auto;
  18. margin-top: 40px;
  19. display: flex;
  20. }
  21. .container{
  22. width: 160px;
  23. /* border: 1px solid #666; */
  24. margin-right: 20px;
  25. }
  26. .container img{
  27. width: 150px;
  28. height: 150px;
  29. }
  30. .title{
  31. font-size: 14px;
  32. }
  33. .name{
  34. color: #666;
  35. font-size: 12px;
  36. }
  37. </style>
  38. </head>
  39. <body>
  40. <div id="app">
  41. </div>
  42. </body>
  43. </html>