浏览代码

HW_16_test

Graf15 2 年之前
父节点
当前提交
9b4a24f2c9

+ 74 - 0
js/js_16_async_architecture_promises/index.html

@@ -0,0 +1,74 @@
+<!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">
+    <link rel="stylesheet" href="style.css">
+    <title>Document</title>
+    
+</head>
+<body>
+    
+    
+    <script>
+        function buttonVisionText(button, element, innertext) {
+    element.innerText = innertext
+    button.innerText = 'Скрыть'
+    button.onclick = () => buttonHidetext(button, element, innertext)
+  }
+  
+  function buttonHidetext(button, element, innertext) {
+    element.innerText = ""
+    button.innerText = 'Показать'
+    button.onclick = () => buttonVisionText(button, element, innertext)
+  }
+
+  function jsonToTable(parent = document.body, jsonObj){
+      const jsonTable = document.createElement('table') //Создаём и добавляем в родительский єлемент будущую таблицу
+      parent.append(jsonTable)
+
+      for (const key in jsonObj){
+          const tr = document.createElement('tr') //одно свойтсво - одна строка
+          jsonTable.append(tr)
+          
+          const tdProperty = document.createElement('td') //столбик со свойствами обьекта
+          tr.append(tdProperty)
+          tdProperty.innerText = key
+
+          const tdValue = document.createElement('td') // столбик со значениями свойств обьекта JSON
+          tr.append(tdValue)
+                    
+          let regexp = /^\s*https?:\/\/./i; //тут проверяем является ли значение ссылкой
+          if ( regexp.test(jsonObj[key]) ) {
+
+            const button = document.createElement('button') // если да то создаём кнопку, текст изначально скрыт
+            tdValue.append(button)
+            button.innerText = 'Показать'
+
+            let value 
+
+            //при первом нажатии получаем данные по ссылке, сохраняем в value и выводим
+
+            button.onclick = () => {
+              fetch(jsonObj[key]) 
+              .then(res => res.text())
+              .then(txt => {
+                tdValue.innerText = txt
+                button.innerText = 'Cкрыть'
+                button.onclick = () => buttonHidetext(button, tdValue, txt)
+              })
+            }
+          }else{
+            tdValue.innerText = jsonObj[key] //если значение не является ссылкой, запихиваем занчение в innertext 
+          }
+      }
+  }
+
+  fetch('https://swapi.dev/api/people/1/')
+    .then(res => res.json())
+    .then(jsonObj => jsonToTable(document.body, jsonObj))
+    </script>
+</body>
+
+</html>

+ 88 - 0
js/js_16_async_architecture_promises/index.js

@@ -0,0 +1,88 @@
+/*fetch basic
+Исследуйте сайт swapi.dev, рассмотрите JSON-ы, которые предоставляются этим сервисом (например: https://swapi.dev/api/people/1/, https://swapi.dev/api/people/2/, https://swapi.dev/api/starships/12/
+С помощью следующего кода считать и вывести информацию о Люке Скайвокере:
+fetch('https://swapi.dev/api/people/1/')
+  .then(res => res.json())
+  .then(luke => console.log(luke))
+Напишите функцию для отображения любого JSON в форме таблицы. Функция должна принимать два параметра:
+DOM - элемент, в котором строится таблица
+JSON, который нужно отобразить.*/
+{
+  function jsonToTable(parent = document.body, jsonObj){
+      const jsonTable = document.createElement('table') //Создаём и добавляем в родительский єлемент будущую таблицу
+      parent.append(jsonTable)
+
+      for (const key in jsonObj){
+          const tr = document.createElement('tr') //одно свойтсво - одна строка
+          jsonTable.append(tr)
+          const tdProperty = document.createElement('td') //столбик со свойствами обьекта
+          tr.append(tdProperty)
+          tdProperty.innerText = key
+          const tdValue = document.createElement('td') // столбик со значениями свойств обьекта JSON
+          tr.append(tdValue)
+          tdValue.innerText = jsonObj[key]
+      }
+  }
+
+  fetch('https://swapi.dev/api/people/1/')
+.then(res => res.json())
+.then(jsonObj => jsonToTable(document.body, jsonObj))
+}
+
+/* fetch improved
+Расширить функцию отображения:
+Если одно из полей строка или массив.
+Если строки или строка содержат в себе https://swapi.dev/api/
+То выводить вместо текста строки кнопку, при нажатии на которую:
+делается fetch данных по этой ссылке
+функция отображения запускает сама себя(рекурсивно) для отображения новых данных в том же элементе.*/
+
+
+{
+  function buttonVisionText()
+
+  function jsonToTable(parent = document.body, jsonObj){
+      const jsonTable = document.createElement('table') //Создаём и добавляем в родительский єлемент будущую таблицу
+      parent.append(jsonTable)
+
+      for (const key in jsonObj){
+          const tr = document.createElement('tr') //одно свойтсво - одна строка
+          jsonTable.append(tr)
+          const tdProperty = document.createElement('td') //столбик со свойствами обьекта
+          tr.append(tdProperty)
+          tdProperty.innerText = key
+          const tdValue = document.createElement('td') // столбик со значениями свойств обьекта JSON
+          tr.append(tdValue)
+          let regexp = /^\s*https?:\/\/./i; //тут проверяем является ли значение ссылкой
+          if ( regexp.test(jsonObj[key]) ) { 
+            const button = document.createElement('button')
+            tdValue.append(button)
+            button.innerText = 'Показать'
+            button.onclick = () => { fetch(jsonObj[key])
+            .then(res => res.text())
+            .then(txt => {
+              tdValue.innerText = txt
+              button.innerText = 'скрыть'
+            })}
+          }else{
+          tdValue.innerText = jsonObj[key] //если не является запихиваем занчение в innertext 
+          }
+      }
+  }
+
+  fetch('https://swapi.dev/api/people/1/')
+.then(res => res.json())
+.then(jsonObj => jsonToTable(document.body, jsonObj))
+}
+
+const value = 'nhfnfnfn'
+const td = document.createElement('td')
+
+
+const button = document.createElement('button')
+button.innerText = 'Показать'
+function buttonVisionText(element, text) {
+
+}
+
+function buttonHidetext()

+ 57 - 0
js/js_16_async_architecture_promises/style.css

@@ -0,0 +1,57 @@
+*,
+*:before,
+*:after {
+  box-sizing: border-box;
+}
+
+body {
+    margin: 0;
+    height: 100vh;
+    background-color: darkgrey;
+
+}
+
+.productCard{
+  padding: 10px;
+  margin: 20px;
+  width: 200px;
+  background-color: azure;
+  border-radius: 10px;
+}
+
+.productName{
+  text-align: center;
+  background-color: rgb(231, 30, 8);
+  padding: 5px;
+  color: white;
+  border-radius: 5px;
+  margin-top: 0px;
+}
+
+.productPrice{
+  text-align: center;
+  padding: 8px;
+  background-color: green;
+  color: white;
+  border-radius: 5px;
+}
+
+.showcase{
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+
+.productQuantity{
+  padding: 10px 0px 50px;
+  text-align: center;
+}
+
+.orderSection{
+  display: flex;
+  justify-content: center;
+}
+
+.orderSection * {
+margin: 10px
+}