|
| 1 | +const URL = 'https://dog.ceo/api/breeds/image/random'; |
| 2 | +const xmlBtn = document.getElementById('xmlBTN'); |
| 3 | +const axiosBtn = document.getElementById('axiosBTN'); |
| 4 | +const ulElm = document.getElementById('list'); |
| 5 | +const imgSize = '300px'; |
| 6 | +ulElm.style.display = 'flex'; |
| 7 | +ulElm.style.flexWrap = 'wrap'; |
| 8 | + |
| 9 | +xmlBtn.addEventListener('click',requestWithXHR); |
| 10 | +axiosBtn.addEventListener('click',requestWithAxios); |
| 11 | + |
| 12 | + |
| 13 | +function requestWithXHR() { |
| 14 | + const xhr = new XMLHttpRequest(); |
| 15 | + xhr.open('GET', URL, true); |
| 16 | + xhr.send(); |
| 17 | + |
| 18 | + // 4. This will be called after the response is received |
| 19 | + xhr.onload = function() { |
| 20 | + if (xhr.status != 200 && xhr.status != 200) { |
| 21 | + // analyze HTTP status of the response |
| 22 | + console.log(`Error ${xhr.status}: ${xhr.statusText}`); // e.g. 404: Not Found |
| 23 | + } else { |
| 24 | + // show the result |
| 25 | + const response = JSON.parse(xhr.responseText); |
| 26 | + const liElm = document.createElement('li'); |
| 27 | + const imgElm = document.createElement('img'); |
| 28 | + imgElm.src = response.message; |
| 29 | + imgElm.style.height = imgSize; |
| 30 | + liElm.style.listStyle = 'none'; |
| 31 | + liElm.appendChild(imgElm); |
| 32 | + ulElm.appendChild(liElm); |
| 33 | + } |
| 34 | + }; |
| 35 | + |
| 36 | + xhr.onprogress = function(event) { |
| 37 | + if (event.lengthComputable) { |
| 38 | + console.log(`Received ${event.loaded} of ${event.total} bytes`); |
| 39 | + } else { |
| 40 | + console.log(`Received ${event.loaded} bytes`); // no Content-Length |
| 41 | + } |
| 42 | + }; |
| 43 | + |
| 44 | + xhr.onerror = function() { |
| 45 | + console.log('Request failed'); |
| 46 | + }; |
| 47 | +} |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | +function requestWithAxios(){ |
| 52 | + axios.get(URL) |
| 53 | + .then(function (response) { |
| 54 | + // handle success |
| 55 | + const liElm = document.createElement('li'); |
| 56 | + const imgElm = document.createElement('img'); |
| 57 | + imgElm.src = response.data.message; |
| 58 | + imgElm.style.height = imgSize; |
| 59 | + liElm.style.listStyle = 'none'; |
| 60 | + liElm.appendChild(imgElm); |
| 61 | + ulElm.appendChild(liElm); |
| 62 | + }) |
| 63 | + .catch(function (error) { |
| 64 | + // handle error |
| 65 | + console.log("Request failed"); |
| 66 | + }) |
| 67 | + .then(function () { |
| 68 | + // always executed |
| 69 | + }); |
| 70 | +}; |
0 commit comments