123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>JS12</title>
- </head>
- <body>
- <select name="country" id="countrySel"></select>
- <select name="city" id="citySel"></select>
- <script>
- //JSON. Загрузить используя XMLHttpRequest и распарсить как ассоциативный массив.
- var request = new XMLHttpRequest() //Создаём новый объект XMLHttpRequest
- request.open('GET', 'https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json', false) // последний параметр указывает на синхронность или асинхронность запроса. В данном случае запрос синхронный
- request.send() // висим пока получаем данные если синхронный запрос, или быстро проскакиваем в случае асинхронного запроса
- if (request.status == 200) {
- alert('all ok')
- //console.log(request.responseText)
- data = JSON.parse(request.responseText)// responseText--Тело ответа сервера, которое мы формируем в JSON строку
- //console.log(data)//data --распарсенный ассоциативный массив(объект)
- var countrySel = document.getElementById('countrySel')
- var citySel = document.getElementById('citySel')
- for (var country in data) {
- var option = document.createElement('option')
- countrySel.appendChild(option)
- option.innerText = country
- }
- countrySel.onchange = function () {
- while (citySel.firstChild) {
- console.log(citySel.firstChild)
- citySel.removeChild(citySel.firstChild);
- }
- console.log(citySel.firstChild)
- for (var country in data) {
- for (var city of data[country]) {
- if (countrySel.value == country) {
- var option = document.createElement('option')
- citySel.appendChild(option)
- option.innerText = city
- // console.log(countrySel.firstChild)
- //console.log(citySel.firstChild)
- } else {}
- }
- }
- }
- } else {
- alert('shit happens: ' + request.status + ', ' + request.statusText);
- }
- </script>
- </body>
- </html>
|