1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- let container = document.createElement('div');
- document.body.append(container);
- fetch('https://swapi.dev/api/people/1/')
- .then(res => res.json())
- .then(luke => createTable(container, luke));
- function createTable(parent, json) {
- let table = document.createElement("table");
- table.setAttribute("border", 1);
- for (let key in json) {
- const tr = document.createElement("tr");
- table.append(tr);
- const th = document.createElement("th");
- th.innerText = key;
- const td = document.createElement("td");
- if (json[key].toString().startsWith("https://")) {
- const button = document.createElement("button");
- button.innerText = "GET INFORMATION";
- button.style = 'width: 100%';
- td.append(button);
- if (Array.isArray(json[key])) {
- let links = json[key];
- links.forEach((link) => {
- button.addEventListener("click", () => f(container, link));
- })
- } else {
- button.addEventListener("click", () => f(container, json[key]));
- }
- } else {
- td.innerText = json[key];
- }
- tr.append(th, td);
- console.log(json[key]);
- }
- parent.append(table);
- }
- function f(cont, link) {
- fetch(link)
- .then((res) => res.json())
- .then((res) => createTable(cont, res));
- }
- ////////////////////////////////////////////////////////
- const url = 'https://swapi.dev/api/people/1/';
- function fetchXML(url) {
- return new Promise((resolve, reject) => {
- const xhr = new XMLHttpRequest();
- xhr.open('GET', url);
-
- xhr.responseType = 'json';
-
- xhr.onload = () => {
- if (xhr.status >= 400) {
- reject(xhr.response)
- } else {
- resolve(xhr.response)
- }
- }
-
- xhr.onerror = () => {
- reject(xhr.response)
- }
-
- xhr.send()
- })
- }
- fetchXML(url)
- .then(data => console.log(data))
- ///////////////////////////////////////////////////////
- const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
- Promise.race([delay(100), fetchXML(url)]).then((result) => console.log(result))
|