script.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. let url = 'https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json';
  2. let request = new XMLHttpRequest();
  3. request.open("GET", url, true);
  4. request.onreadystatechange = () => {
  5. if (request.readyState == 4){
  6. let countriesFromJson = JSON.parse(request.response);
  7. showCountry(countriesFromJson);
  8. countrySelect.oninput = () => {
  9. showCities(countrySelect.value, countriesFromJson);
  10. }
  11. }
  12. }
  13. request.send()
  14. function showCountry(obj){
  15. for (let [key,val] of Object.entries(obj)){
  16. let option = document.createElement('option');
  17. option.innerText = key
  18. countrySelect.append(option)
  19. }
  20. showCities(countrySelect.value, obj);
  21. }
  22. function showCities(country, object){
  23. citySelect.innerText = ''
  24. let citiesFromCurrentCountry = object[country];
  25. citiesFromCurrentCountry.forEach((item) => {
  26. let option = document.createElement('option');
  27. option.innerText = item
  28. citySelect.append(option)
  29. });
  30. }
  31. ////////////////////////////////////////////////////////fetch basic, fetch improved
  32. let url2 = 'https://swapi.dev/api/people/1/';
  33. let valueCreators = {
  34. String(value){
  35. if(value.includes("https://swapi.dev/api/")){
  36. return `<button>${value}</button>`
  37. } else {
  38. return value
  39. }
  40. },
  41. Array(value){
  42. let str = '';
  43. value.forEach((item) => {
  44. item.includes("https://swapi.dev/api/") ? str += `<button>${item}</button>` : str += item
  45. })
  46. return str
  47. }
  48. }
  49. function createTable(parent, obj){
  50. let str = '<table border="2">';
  51. for(let [key,value] of Object.entries(obj)){
  52. let valueCreator = valueCreators[value.constructor.name];
  53. if (typeof valueCreator === 'function'){ ///проверяем значение (есть ли для него нужный конструктор)
  54. str += `<tr><td>${key}</td><td>${valueCreator(value)}</td></tr>`
  55. } else {
  56. str += `<tr><td>${key}</td><td>${value}</td></tr>`
  57. }
  58. }
  59. str += '</table>'
  60. parent.innerHTML += str;
  61. }
  62. let startFetch = function (url,parent){ ////создает новую таблицу в том элементе где была кнопка
  63. fetch(url)
  64. .then(res => res.json())
  65. .then(luke => createTable(parent, luke))
  66. }
  67. startFetch(url2, container);
  68. container.addEventListener("click", (event) => {
  69. if(event.target.tagName == 'BUTTON'){
  70. startFetch(event.target.textContent, event.target.parentElement)
  71. }
  72. })
  73. // let startFetch = function (url){ ///// или можно все перезатирать и создавать новую (без наглядной вложенности)
  74. // fetch(url) ///// только в 72 строке изменить на parent.innerHTML = str;
  75. // .then(res => res.json())
  76. // .then(luke => createTable(container, luke))
  77. // }
  78. // startFetch(url2);
  79. // container.addEventListener("click", (event) => {
  80. // if(event.target.tagName == 'BUTTON'){
  81. // startFetch(event.target.textContent)
  82. // }
  83. // })
  84. /////////////////////////////////////////////// my fetch
  85. let url3 = 'https://swapi.dev/api/people/1/';
  86. function myFetch (url){
  87. return new Promise(function (resolve, reject){
  88. const xhr = new XMLHttpRequest();
  89. xhr.open("GET", url, true);
  90. xhr.onreadystatechange = () => {
  91. if(xhr.readyState == 4){ ///проверяем закончился ли запрос
  92. if (xhr.status == 200){
  93. resolve(JSON.parse(xhr.response))
  94. } else if (xhr.onerror || xhr.status != 200){
  95. reject(new Error(`i have error for you ${xhr.status} ${xhr.statusText}`))
  96. }
  97. }
  98. }
  99. xhr.send()
  100. })
  101. }
  102. myFetch(url3).then(luke => console.log(luke));
  103. ////////////////////race
  104. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms));
  105. Promise.race([myFetch(url3), delay(350)]).then(value => console.log(value));