|
| 1 | +/* eslint-disable no-console */ |
| 2 | + |
| 3 | +'use strict'; |
| 4 | + |
| 5 | +{ |
| 6 | + function loadText() { |
| 7 | + // Create XHR Object |
| 8 | + const xhr = new XMLHttpRequest(); |
| 9 | + // OPEN - type, url/file, async |
| 10 | + xhr.open('GET', 'sample.txt', true); |
| 11 | + |
| 12 | + console.log('READYSTATE: ', xhr.readyState); |
| 13 | + |
| 14 | + // OPTIONAL - used for loaders |
| 15 | + xhr.onprogress = () => { |
| 16 | + console.log('READYSTATE: ', xhr.readyState); |
| 17 | + }; |
| 18 | + |
| 19 | + xhr.onload = () => { |
| 20 | + console.log('READYSTATE: ', xhr.readyState); |
| 21 | + if (xhr.status === 200) { |
| 22 | + // console.log(this.responseText); |
| 23 | + document.getElementById('text').innerHTML = xhr.responseText; |
| 24 | + } else if (this.status === 404) { |
| 25 | + document.getElementById('text').innerHTML = 'Not Found'; |
| 26 | + } |
| 27 | + }; |
| 28 | + |
| 29 | + xhr.onerror = () => { |
| 30 | + console.log('Request Error...'); |
| 31 | + }; |
| 32 | + |
| 33 | + // xhr.onreadystatechange = () => { |
| 34 | + // console.log('READYSTATE: ', xhr.readyState); |
| 35 | + // if xhr.readyState === 4 && xhr.status === 200){ |
| 36 | + // //console.log(this.responseText); |
| 37 | + // } |
| 38 | + // } |
| 39 | + |
| 40 | + // Sends request |
| 41 | + xhr.send(); |
| 42 | + } |
| 43 | + |
| 44 | + // readyState Values |
| 45 | + // 0: request not initialized |
| 46 | + // 1: server connection established |
| 47 | + // 2: request received |
| 48 | + // 3: processing request |
| 49 | + // 4: request finished and response is ready |
| 50 | + |
| 51 | + // HTTP Statuses |
| 52 | + // 200: "OK" |
| 53 | + // 403: "Forbidden" |
| 54 | + // 404: "Not Found" |
| 55 | + |
| 56 | + document.getElementById('button').addEventListener('click', loadText); |
| 57 | +} |
0 commit comments