fetch.html 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <script>
  10. fetch('https://swapi.dev/api/people/1/')
  11. .then(res => res.json())
  12. .then(luke => objectToDm(document.body, luke))
  13. function objectToDm(el, data) {
  14. let table = document.createElement("table")
  15. table.border = 1
  16. el.appendChild(table)
  17. for (let key in data) {
  18. let row = document.createElement("tr");
  19. table.appendChild(row);
  20. let name = document.createElement("th");
  21. name.innerText = key;
  22. row.appendChild(name);
  23. if(data[key] instanceof Array) {
  24. for (let aboutLink of data[key]) {
  25. let about = document.createElement("td");
  26. about.style = "border: 2px solid black";
  27. row.appendChild(about)
  28. if(aboutLink.includes("http")) {
  29. let button = document.createElement("button");
  30. button.innerText = aboutLink;
  31. button.onclick = () => {
  32. fetch(`${button.innerText}`)
  33. .then(res => res.json())
  34. .then(direction => objectToDm(document.body, direction))
  35. }
  36. about.appendChild(button);
  37. }
  38. }
  39. } else {
  40. let about = document.createElement("td");
  41. about.style = "border: 2px solid black";
  42. row.appendChild(about)
  43. if(`${data[key]}`.includes("http")) {
  44. let button = document.createElement("button");
  45. button.innerText = data[key];
  46. button.onclick = () => {
  47. fetch(`${button.innerText}`)
  48. .then(res => res.json())
  49. .then(direction => objectToDm(document.body, direction))
  50. }
  51. about.appendChild(button);
  52. } else {
  53. about.innerText = `${data[key]}`;
  54. }
  55. }
  56. }
  57. }
  58. </script>
  59. </body>
  60. </html>