main.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. fetch('https://swapi.dev/api/people/1/')
  2. .then(res => res.json())
  3. .then(data => renderTree(root, data))
  4. const renderTree = (el, json) => {
  5. let table = document.createElement('table')
  6. table.setAttribute('border', '1px')
  7. for (const [key, value] of Object.entries(json)) {
  8. let tr = document.createElement('tr')
  9. let th = document.createElement('th')
  10. let td = document.createElement('td')
  11. let button = document.createElement('button')
  12. th.innerText = key
  13. if (typeof (value) === 'object') {
  14. let deepTable = document.createElement('table')
  15. deepTable.setAttribute('border', '1px')
  16. deepTable.style.width = '100%'
  17. value.map(t => {
  18. let deepTr = document.createElement('tr')
  19. let deepTd = document.createElement('td')
  20. let deepButton = document.createElement('button')
  21. deepButton.innerText = t.slice(22, -1)
  22. deepButton.onclick = () => reRenderTree(deepTd, t)
  23. deepTd.append(deepButton)
  24. deepTr.append(deepTd)
  25. deepTable.append(deepTr)
  26. })
  27. td.append(deepTable)
  28. } else if (typeof value === 'string' && !value.indexOf('https://')) {
  29. button.innerText = value.slice(22,-1)
  30. button.onclick = () => reRenderTree(td, value)
  31. td.append(button)
  32. } else {
  33. /\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*/.test(value) ? td.innerText = value.slice(0, 10) : td.innerText = value
  34. }
  35. tr.append(th)
  36. tr.append(td)
  37. table.append(tr)
  38. }
  39. el.append(table)
  40. }
  41. const reRenderTree = (el, link) => {
  42. el.removeChild(el.firstChild)
  43. return fetch(link)
  44. .then(res => res.json())
  45. .then(data => renderTree(el, data))
  46. }
  47. function myfetch(url) {
  48. return new Promise(function (resolve, reject) {
  49. const xhr = new XMLHttpRequest()
  50. xhr.open('GET', url, true)
  51. xhr.onreadystatechange = function () {
  52. if (xhr.readyState != 4) {
  53. return;
  54. }
  55. if (xhr.status == 200) {
  56. resolve(JSON.parse(xhr.responseText))
  57. }
  58. else {
  59. reject(new Error('Error ' + xhr.status + ', ' + xhr.statusText))
  60. }
  61. }
  62. xhr.send()
  63. })
  64. }
  65. myfetch('https://swapi.dev/api/people/1/').then(luke => console.log(luke)).catch(e => console.log(e))
  66. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  67. let arr = Promise.race([delay(900), myfetch('https://swapi.dev/api/people/1/')])
  68. console.log(arr);