123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <div id="LukeSkywalker"></div>
- <script>
- // ****** fetch basic-fetch improved1 *******//
- div = document.getElementById('LukeSkywalker')
- function darkSide(DOM, JASON) {
- let obj = JASON
- let table = document.createElement('table')
- table.setAttribute('style', "display: inline-block; border:1px; margin: 30px 15px; border-style:solid; border-color:#FF0000;")
- let stringUrl = 'https://swapi.dev/api/'
- for (const iterator in obj) {
- let row = document.createElement('tr')
- row.setAttribute('style', 'padding:15px;')
- row.innerHTML = iterator.toUpperCase() + ":";
- table.appendChild(row)
- let cell = document.createElement('td')
- //console.log(obj[iterator])
- try {
- if (obj[iterator].indexOf(stringUrl) > -1) {
- let button = document.createElement('button')
- button.innerHTML = "show"
- cell.appendChild(button)
- button.onclick = function () {
- fetch(`${obj[iterator]}`)
- .then(res => res.json())
- .then(anyJson => darkSide(DOM, anyJson))
- }
- }
- else if (typeof obj[iterator] === 'object') {
- for (let j = 0; j < obj[iterator].length; j++) {
- let button = document.createElement('button')
- button.innerHTML = "show"
- button.onclick = function () {
- fetch(`${obj[iterator][j]}`)
- .then(res => res.json())
- .then(anyJson => darkSide(DOM, anyJson))
- }
- cell.appendChild(button)
- }
- } else
- cell.innerHTML = obj[iterator]
- cell.setAttribute('style', "border: 1px; border-style: solid; border-color:#FF0000; text-align: center; ")
- row.appendChild(cell)
- }
- catch (e) {
- console.log(e)
- }
- }
- DOM.appendChild(table)
- }
- fetch('https://swapi.dev/api/people/1/')
- .then(res => res.json())
- .then(luke => darkSide(div, luke))
- //******** myFetch ************//
- function myfetch(url) {
- return new Promise(function (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.send();
- })
- }
- myfetch('https://swapi.dev/api/people/1/')
- .then(luke => console.log(luke))
- //******** race ************//
- const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
- console.log(Promise.race([myfetch('https://swapi.dev/api/people/1/'), delay(Math.random() * 1000)]))
- </script>
- </body>
- </html>
|