瀏覽代碼

HW12 done

vladislavaSim 1 年之前
父節點
當前提交
2f22452b77
共有 1 個文件被更改,包括 38 次插入19 次删除
  1. 38 19
      HW12/main.js

+ 38 - 19
HW12/main.js

@@ -1,18 +1,13 @@
 fetch('https://swapi.dev/api/people/1/')
     .then(res => res.json())
-    .then(luke => renderTable(luke))
+    .then(luke => renderTable(document.body, luke))
 
-fetch('https://swapi.dev/api/people/1/')
-    .then(res => res.json())
-    .then(luke => console.log(luke))
-
-function renderTable(obj) {
+function renderTable(parent, obj) {
     let $table = document.createElement('table')
     for(let key in obj) {
         let $tr = document.createElement('tr')
         let $td = document.createElement('td')
         let $td2 = document.createElement('td')
-        console.log(obj[key])
         if(Array.isArray(obj[key])) {
             for(let item of obj[key]) {
                 let newTable = document.createElement('table')
@@ -32,19 +27,43 @@ function renderTable(obj) {
         $tr.append($td, $td2)
         $table.appendChild($tr)
     }
-    document.body.appendChild($table)
-
-
+    parent.appendChild($table)
 }
 function linkChecker(str, container) {
-    if(str.includes('https://swapi.dev/api/')) {
-        let btn = document.createElement('button')
-        btn.innerHTML = 'Show'
-        btn.onclick = () => {
-            location = str
+    if(typeof str === 'string') {
+        if(str.includes('https://swapi.dev/api/')) {
+            let btn = document.createElement('button')
+            btn.innerHTML = 'Show'
+            btn.onclick = () => {
+                fetch(str).then(r => r.json())
+                    .then(r => renderTable(container, r))
+                    // .then(r => console.log(r))
+            }
+            container.append(btn)
+        } else {
+            container.innerHTML = str
         }
-        container.append(btn)
-    } else {
-        container.innerHTML = str
     }
-}
+}
+//
+// function myFetch(url){
+//     return new Promise(function (resolve, reject){
+//         const xhr = new XMLHttpRequest()
+//         xhr.open('get', url)
+//         xhr.onload = function () {
+//             if (xhr.status >= 200 && xhr.status < 300) {
+//                 resolve(xhr.response);
+//             } else {
+//                 reject(() => alert('something went wrong'));
+//             }
+//         xhr.send();
+//     }});
+// }
+// myFetch('https://swapi.dev/api/peope/4/')
+//     .then(res => console.log(res))
+//
+// function delay(ms) {
+//     return setTimeout(() => console.log('delay worked'), ms)
+// }
+// Promise.race([myFetch('https://swapi.dev/api/peope/4/'), delay(300)]).then(val => console.log(val))
+// Promise.race([myFetch('https://swapi.dev/api/peope/1/'), delay(200)]).then(val => console.log(val))