index.html 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>JS12</title>
  7. </head>
  8. <body>
  9. <select name="country" id="countrySel"></select>
  10. <select name="city" id="citySel"></select>
  11. <script>
  12. //JSON. Загрузить используя XMLHttpRequest и распарсить как ассоциативный массив.
  13. var request = new XMLHttpRequest() //Создаём новый объект XMLHttpRequest
  14. request.open('GET', 'https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json', false) // последний параметр указывает на синхронность или асинхронность запроса. В данном случае запрос синхронный
  15. request.send() // висим пока получаем данные если синхронный запрос, или быстро проскакиваем в случае асинхронного запроса
  16. if (request.status == 200) {
  17. alert('all ok')
  18. //console.log(request.responseText)
  19. data = JSON.parse(request.responseText)// responseText--Тело ответа сервера, которое мы формируем в JSON строку
  20. //console.log(data)//data --распарсенный ассоциативный массив(объект)
  21. var countrySel = document.getElementById('countrySel')
  22. var citySel = document.getElementById('citySel')
  23. for (var country in data) {
  24. var option = document.createElement('option')
  25. countrySel.appendChild(option)
  26. option.innerText = country
  27. }
  28. countrySel.onchange = function () {
  29. while (citySel.firstChild) {
  30. console.log(citySel.firstChild)
  31. citySel.removeChild(citySel.firstChild);
  32. }
  33. console.log(citySel.firstChild)
  34. for (var country in data) {
  35. for (var city of data[country]) {
  36. if (countrySel.value == country) {
  37. var option = document.createElement('option')
  38. citySel.appendChild(option)
  39. option.innerText = city
  40. // console.log(countrySel.firstChild)
  41. //console.log(citySel.firstChild)
  42. } else {}
  43. }
  44. }
  45. }
  46. } else {
  47. alert('shit happens: ' + request.status + ', ' + request.statusText);
  48. }
  49. </script>
  50. </body>
  51. </html>