فهرست منبع

fetch improved added

vladislavaSim 1 سال پیش
والد
کامیت
a199f8d863
2فایلهای تغییر یافته به همراه72 افزوده شده و 0 حذف شده
  1. 22 0
      HW12/index.html
  2. 50 0
      HW12/main.js

+ 22 - 0
HW12/index.html

@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <title>HW12</title>
+    <style>
+        body {
+            font-size: 20px;
+        }
+        td {
+            border: 1px solid black;
+            padding: 4px;
+        }
+        button {
+            background-color: #C4C4C4;
+        }
+    </style>
+</head>
+<body>
+<script src="main.js"></script>
+</body>
+</html>

+ 50 - 0
HW12/main.js

@@ -0,0 +1,50 @@
+fetch('https://swapi.dev/api/people/1/')
+    .then(res => res.json())
+    .then(luke => renderTable(luke))
+
+fetch('https://swapi.dev/api/people/1/')
+    .then(res => res.json())
+    .then(luke => console.log(luke))
+
+function renderTable(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')
+                let newTr = document.createElement('tr')
+                let newTd = document.createElement('td')
+                linkChecker(item, newTd)
+                newTr.append(newTd)
+                newTable.append(newTr)
+                $td2.append(newTable)
+            }
+        } else {
+            linkChecker(obj[key], $td2)
+        }
+
+        $td.innerHTML = key
+
+        $tr.append($td, $td2)
+        $table.appendChild($tr)
+    }
+    document.body.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
+        }
+        container.append(btn)
+    } else {
+        container.innerHTML = str
+    }
+}