index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. let container = document.createElement('div');
  2. document.body.append(container);
  3. fetch('https://swapi.dev/api/people/1/')
  4. .then(res => res.json())
  5. .then(luke => createTable(container, luke));
  6. function createTable(parent, json) {
  7. let table = document.createElement("table");
  8. table.setAttribute("border", 1);
  9. for (let key in json) {
  10. const tr = document.createElement("tr");
  11. table.append(tr);
  12. const th = document.createElement("th");
  13. th.innerText = key;
  14. const td = document.createElement("td");
  15. if (json[key].toString().startsWith("https://")) {
  16. const button = document.createElement("button");
  17. button.innerText = "GET INFORMATION";
  18. button.style = 'width: 100%';
  19. td.append(button);
  20. if (Array.isArray(json[key])) {
  21. let links = json[key];
  22. links.forEach((link) => {
  23. button.addEventListener("click", () => f(container, link));
  24. })
  25. } else {
  26. button.addEventListener("click", () => f(container, json[key]));
  27. }
  28. } else {
  29. td.innerText = json[key];
  30. }
  31. tr.append(th, td);
  32. console.log(json[key]);
  33. }
  34. parent.append(table);
  35. }
  36. function f(cont, link) {
  37. fetch(link)
  38. .then((res) => res.json())
  39. .then((res) => createTable(cont, res));
  40. }
  41. ////////////////////////////////////////////////////////
  42. const url = 'https://swapi.dev/api/people/1/';
  43. function fetchXML(url) {
  44. return new Promise((resolve, reject) => {
  45. const xhr = new XMLHttpRequest();
  46. xhr.open('GET', url);
  47. xhr.responseType = 'json';
  48. xhr.onload = () => {
  49. if (xhr.status >= 400) {
  50. reject(xhr.response)
  51. } else {
  52. resolve(xhr.response)
  53. }
  54. }
  55. xhr.onerror = () => {
  56. reject(xhr.response)
  57. }
  58. xhr.send()
  59. })
  60. }
  61. fetchXML(url)
  62. .then(data => console.log(data))
  63. ///////////////////////////////////////////////////////
  64. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  65. Promise.race([delay(100), fetchXML(url)]).then((result) => console.log(result))