瀏覽代碼

HWJS12 (fetch,myfetch) done

DimaBondarenko 3 年之前
父節點
當前提交
f0b449f76b
共有 5 個文件被更改,包括 167 次插入0 次删除
  1. 2 0
      HWJS12/css/style.min.css
  2. 9 0
      HWJS12/css/style.min.css.map
  3. 19 0
      HWJS12/index.html
  4. 132 0
      HWJS12/js/script.js
  5. 5 0
      HWJS12/sass/style.scss

+ 2 - 0
HWJS12/css/style.min.css

@@ -0,0 +1,2 @@
+*{-webkit-box-sizing:border-box;box-sizing:border-box;margin:0}
+/*# sourceMappingURL=style.min.css.map */

+ 9 - 0
HWJS12/css/style.min.css.map

@@ -0,0 +1,9 @@
+{
+    "version": 3,
+    "mappings": "AAAA,AAAA,CAAC,AAAA,CACG,UAAU,CAAE,UAAU,CACtB,MAAM,CAAE,CAAC,CACZ",
+    "sources": [
+        "../sass/style.scss"
+    ],
+    "names": [],
+    "file": "style.min.css"
+}

+ 19 - 0
HWJS12/index.html

@@ -0,0 +1,19 @@
+<!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>
+    <link rel="stylesheet" href="css/style.min.css">
+</head>
+<body>
+    <select id="countrySelect">
+        
+    </select>
+    <select id="citySelect"></select>
+
+    <div id="container"></div>
+    <script src="js/script.js"></script>
+</body>
+</html>

+ 132 - 0
HWJS12/js/script.js

@@ -0,0 +1,132 @@
+let url = 'https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json';
+let request = new XMLHttpRequest();
+request.open("GET", url, true);
+
+request.onreadystatechange = () => {
+    if (request.readyState == 4){
+        let countriesFromJson = JSON.parse(request.response);
+        showCountry(countriesFromJson);
+
+        countrySelect.oninput = () => {
+            showCities(countrySelect.value, countriesFromJson);
+        }
+    }
+    
+}
+
+request.send()
+
+function showCountry(obj){
+    for (let [key,val] of Object.entries(obj)){
+
+        let option = document.createElement('option');
+        option.innerText = key
+        countrySelect.append(option)
+    }
+    showCities(countrySelect.value, obj);
+}
+
+function showCities(country, object){
+    citySelect.innerText = ''
+    let citiesFromCurrentCountry = object[country];
+    citiesFromCurrentCountry.forEach((item) => {
+        let option = document.createElement('option');
+        option.innerText = item
+        citySelect.append(option)
+    });
+}
+
+////////////////////////////////////////////////////////fetch basic, fetch improved
+let url2 = 'https://swapi.dev/api/people/1/';
+let valueCreators = {
+    String(value){
+        if(value.includes("https://swapi.dev/api/")){
+            return `<button>${value}</button>`
+        } else {
+            return value
+        }
+    },
+    Array(value){
+        let str = '';
+        value.forEach((item) => {
+            item.includes("https://swapi.dev/api/") ? str += `<button>${item}</button>` : str += item
+        })
+        return str 
+    }
+}
+
+function createTable(parent, obj){
+   
+    let str = '<table border="2">';
+
+    for(let [key,value] of Object.entries(obj)){
+        let valueCreator = valueCreators[value.constructor.name];
+        if (typeof valueCreator === 'function'){                               ///проверяем значение (есть ли для него нужный конструктор)
+            str += `<tr><td>${key}</td><td>${valueCreator(value)}</td></tr>`
+        } else {
+            str += `<tr><td>${key}</td><td>${value}</td></tr>`
+        }
+    }
+
+    str += '</table>'
+    parent.innerHTML += str;
+}
+
+let startFetch = function (url,parent){                      ////создает новую таблицу в том элементе где была кнопка
+    fetch(url)
+    .then(res => res.json())
+    .then(luke => createTable(parent, luke))
+}
+
+startFetch(url2, container);
+
+container.addEventListener("click", (event) => {
+    if(event.target.tagName == 'BUTTON'){
+        startFetch(event.target.textContent, event.target.parentElement)
+    }
+})
+
+// let startFetch = function (url){                      ///// или можно все перезатирать и создавать новую (без наглядной вложенности)
+//     fetch(url)                                        ///// только в 72 строке изменить на parent.innerHTML = str;
+//     .then(res => res.json())
+//     .then(luke => createTable(container, luke))
+// }
+
+// startFetch(url2);
+
+// container.addEventListener("click", (event) => {
+//     if(event.target.tagName == 'BUTTON'){
+//         startFetch(event.target.textContent)
+//     }
+// })
+
+/////////////////////////////////////////////// my fetch
+let url3 = 'https://swapi.dev/api/people/1/';
+function myFetch (url){
+    return new Promise(function (resolve, reject){
+        const xhr = new XMLHttpRequest();
+        xhr.open("GET", url, true);
+        xhr.onreadystatechange = () => {
+
+            if(xhr.readyState == 4){             ///проверяем закончился ли запрос
+                if (xhr.status == 200){
+                    resolve(JSON.parse(xhr.response))
+                } else if (xhr.onerror || xhr.status != 200){
+                    reject(new Error(`i have error for you ${xhr.status} ${xhr.statusText}`))
+                }
+            }
+
+        }
+
+        xhr.send()
+    })
+}
+
+myFetch(url3).then(luke => console.log(luke));
+////////////////////race
+const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms));
+
+Promise.race([myFetch(url3), delay(350)]).then(value => console.log(value));
+
+
+

+ 5 - 0
HWJS12/sass/style.scss

@@ -0,0 +1,5 @@
+*{
+    box-sizing: border-box;
+    margin: 0;
+}
+