1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>axios</title> <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <style> </style> <body> <div class="container"> <h2 class="page-header">ajax</h2> <button class="btn btn-primary">发送GET请求</button> <h3 class="page-header">数据展示</h3> <ul class = 'list'></ul> </div> <script> function myAJAX(method='GET', url='', isAysnc=true, data=null) { let xhr = new XMLHttpRequest();
return new Promise((resolve, reject)=> { xhr.onreadystatechange = function() { if (xhr.readyState !== 4) return; if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { resolve(xhr.responseText); } else { reject(xhr.statusText); } } };
xhr.open(method, url, isAysnc);
xhr.send(data); }); }
function getList(data) { const ul = document.getElementsByTagName('ul')[0]; data.forEach((item, index) => { let li = document.createElement('li'); li.innerHTML = item.name; ul.appendChild(li); }) }
const BASE_URL = 'http://localhost:3000';
const hotSongsRequest = (id) => myAJAX('GET', BASE_URL + '/artist/top/song?id=' + id, true, null);
const btns = document.getElementsByTagName('button');
btns[0].addEventListener('click', () => { let res = hotSongsRequest(6452); res.then(value => { let data = JSON.parse(value); getList(data.songs); }, err => { console.log(err); }) }) </script> </body> </html>
|