main.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. fetch('https://swapi.dev/api/people/1/')
  2. .then(res => res.json())
  3. .then(luke => renderTable(document.body, luke))
  4. function renderTable(parent, obj) {
  5. let $table = document.createElement('table')
  6. for(let key in obj) {
  7. let $tr = document.createElement('tr')
  8. let $td = document.createElement('td')
  9. let $td2 = document.createElement('td')
  10. if(Array.isArray(obj[key])) {
  11. for(let item of obj[key]) {
  12. let newTable = document.createElement('table')
  13. let newTr = document.createElement('tr')
  14. let newTd = document.createElement('td')
  15. linkChecker(item, newTd)
  16. newTr.append(newTd)
  17. newTable.append(newTr)
  18. $td2.append(newTable)
  19. }
  20. } else {
  21. linkChecker(obj[key], $td2)
  22. }
  23. $td.innerHTML = key
  24. $tr.append($td, $td2)
  25. $table.appendChild($tr)
  26. }
  27. parent.appendChild($table)
  28. }
  29. function linkChecker(str, container) {
  30. if(typeof str === 'string') {
  31. if(str.includes('https://swapi.dev/api/')) {
  32. let btn = document.createElement('button')
  33. btn.innerHTML = 'Show'
  34. btn.onclick = () => {
  35. fetch(str).then(r => r.json())
  36. .then(r => renderTable(container, r))
  37. // .then(r => console.log(r))
  38. }
  39. container.append(btn)
  40. } else {
  41. container.innerHTML = str
  42. }
  43. }
  44. }
  45. //
  46. // function myFetch(url){
  47. // return new Promise(function (resolve, reject){
  48. // const xhr = new XMLHttpRequest()
  49. // xhr.open('get', url)
  50. // xhr.onload = function () {
  51. // if (xhr.status >= 200 && xhr.status < 300) {
  52. // resolve(xhr.response);
  53. // } else {
  54. // reject(() => alert('something went wrong'));
  55. // }
  56. // xhr.send();
  57. // }});
  58. // }
  59. // myFetch('https://swapi.dev/api/peope/4/')
  60. // .then(res => console.log(res))
  61. //
  62. // function delay(ms) {
  63. // return setTimeout(() => console.log('delay worked'), ms)
  64. // }
  65. // Promise.race([myFetch('https://swapi.dev/api/peope/4/'), delay(300)]).then(val => console.log(val))
  66. // Promise.race([myFetch('https://swapi.dev/api/peope/1/'), delay(200)]).then(val => console.log(val))