hw_16_02_fetch_improved.html 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <header>
  2. fetch improved
  3. </header>
  4. <body>
  5. <script>
  6. const improovedFetch = (url, el) => {
  7. fetch(url)
  8. .then(res => res.json())
  9. .then(luke => {
  10. let table = document.createElement("table");
  11. for (let key in luke) {
  12. let row = document.createElement("tr");
  13. table.append(row);
  14. let nameTd = document.createElement("td");
  15. nameTd.innerText = key;
  16. row.append(nameTd);
  17. let valueTd = document.createElement("td");
  18. let value = luke[key];
  19. let valueArr = [];
  20. if (typeof value == "string") {
  21. valueArr.push(value);
  22. }
  23. else if (Array.isArray(value)) {
  24. valueArr = value.filter(val => typeof val == "string");
  25. }
  26. valueArr = valueArr.filter(val => val.startsWith("https://swapi.dev/api/"));
  27. if (valueArr.length > 0) {
  28. for (let urlStr of valueArr) {
  29. let div = document.createElement("div");
  30. valueTd.append(div);
  31. let button = document.createElement("button");
  32. button.onclick = () => {
  33. button.style.display = "none";
  34. improovedFetch(urlStr, div);
  35. };
  36. valueTd.append(button);
  37. }
  38. }
  39. else {
  40. valueTd.innerText = luke[key];
  41. }
  42. row.append(valueTd);
  43. }
  44. table.border = "1";
  45. el.append(table);
  46. });
  47. }
  48. improovedFetch('https://swapi.dev/api/people/1/', document.body);
  49. </script>
  50. </body>