Обработка XML ответа от сервера и выборка данных, в чем беда?

Проблема такова, есть страница:
https://pogoda.yandex.ru/static/cities.xml


Есть PHP код:
<?php
$URI = $_GET['uri'];
if ($_GET['region'] != "") {
	$URI .= "?region=".$_GET['region'];
}
$str = file_get_contents($URI);
echo $str;
?>


есть JavaScript код:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" /> 
 <script src="http://code.jquery.com/jquery-3.1.1.js"></script>
</head>
<body>
  <div id="wrapper">
     <div id="form">
      <label> Введите название города:</label><input type="text" name="CityName"><br>
      <button OnClick="getCities();">Посмотреть Геоданные</button>
    </div>
    <div id="geo"></div>
  </div>
  <div id="success"></div>
  <script src="http://code.jquery.com/jquery-3.1.1.js"></script>
  <script>
  // города: https://pogoda.yandex.ru/static/cities.xml
  // погоды: http://export.yandex.ru/bar/reginfo.xml?region=ID

  var cities;
  var countries;


  function getXmlHttp(){
    var xmlhttp;
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
      xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
  }



  function getCities() {
    var req = getXmlHttp();

    req.onreadystatechange = function() { 
      if (req.readyState == 4) {
        if(req.status == 200) {
          $("#success").html(req.responseText);
          cities = req.responseText;
          alert(cities);
/*Ошибка вот тут ->*/ alert(cities[1].getElementsByTagName('cities').getElementsByTagName('city')[0].getAttribute("region"));
          countries = cities.getElementsByName("cities")[0].getElementsByTagName("country");
          if(countries)
          for(var i=0; i<countries.length; i++){
            for (var j=0; j<countries[i].getElementsByTagName('city').length; j++)
            {
              alert(countries[i].getElementsByTagName('city')[j].innerHTML);
              if (document.getElementsByName('CityName')[0].value == countries[i].getElementsByTagName('city')[j].innerHTML) {
                getGeo(countries[i].getElementsByTagName('city')[j].getAttribute("region"));
              }
            }
          }
        } else {
          alert('Ошибка');
        }
      }
    }
    req.open('GET', 'getcontent.php?uri=https://pogoda.yandex.ru/static/cities.xml', true);
    req.send(null);
  }

  function getGeo(cityID) {
    var req2 = getXmlHttp();

    req2.onreadystatechange = function() { 
      if (req.readyState == 4) {
        if(req.status == 200) {
          $("#geo").html(req.responseText);
        } else {
          alert('Ошибка');
        }
      }
    }
    req2.open('GET', 'getcontent.php?uri=http://export.yandex.ru/bar/reginfo.xml&region='+cityID, true);
    req2.send(null);
  }
  </script>
</body>
</html>


нужно по ссылке получить определенный аргумент тега city, а именно region и выполнить вторую функцию с запросом.

но при парсинге XML в первом запросе выдает ошибку:
Uncaught TypeError: cities[1].getElementsByTagName is not a function
at XMLHttpRequest.req.onreadystatechange ((index):53)


Прошу помощи в получении и обработке полученного с запроса XML, а дальше уже я сам.
  • Вопрос задан
  • 471 просмотр
Решения вопроса 1
@YemSalat
> cities = req.responseText;
потому что cities - это строка?

а cities[1] - это второй символ в строке, а не DOM объект
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы