2016-06-18 4 views
0

Я получаю сообщение «Не могу прочитать свойство« 0 »неопределенной ошибки. Я не мог найти проблему. Я думаю, что у javascript-файла есть проблема, но я не мог видеть. Я написал сценарий дважды, но у js-файла есть проблема.Невозможно прочитать свойство '0' of undefined

HTML файла

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
     "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <title>FreeCodeCamp - Local Weather</title> 
    <script src="https://code.jquery.com/jquery-3.0.0.js"></script> 
    <script type="text/javascript" src="app.js"></script> 
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> 
    <link rel="stylesheet" type="text/css" href="style.css"/> 
</head> 

<body> 
<div id="main" class="text-center container"> 
    <h1>FreeCodeCamp - Weather App</h1> 
    <div class="row" id="fade"> 
     <div style="margin-top: 200px;"> 
      <span id="city"></span> 
      <span id="country"></span> 
      <div id="weather"><img id="w-icon"><span id="temp"></span></div> 
      <span id="description"></span> 
     </div> 
    </div> 
    <div id="author"> 
     <span> Created by Kaan Karaca</span><br> 
     <span><a href="http://github.com/h4yfans">@GitHub</a> </span><br> 
     <span><a href="https://www.freecodecamp.com/h4yfans">@FreeCodeCamp</a> </span> 
    </div> 

</div> 
</body> 
</html> 

JavaScript Файл

$(document).ready(function() { 
var cityId; 
var city; 
var unitsFormat = "metric"; 

var getWeatherInfo = function() { 
    $.getJSON("http://api.sypexgeo.net/json") 
     .done(function (locationData) { 
      cityId = locationData.city.id; 
      cityName = locationData.country.iso; 

      $.getJSON("http://api.openweathermap.org/data/2.5/weather?", { 
       id: cityId, 
       units: unitsFormat, 
       APPID: '610ae7b6406da76bb34ad4bb95cc3673' 
      }) 
       .done(function (weatherDate) { 
        $("#w-icon").attr("src", "http://openweathermap.org/img/w/" + weatherDate.weather[0].icon + ".png"); 
        $("#temp").text(Math.round(weatherDate.main.temp) + "°C"); 
        $("#city").text(weatherDate.name + ","); 
        $("#country").text(cityName); 
        $("#description").text(weatherDate.weather[0].description); 

       }); 
     }); 
} 

getWeatherInfo(); 

}); 
+0

Возможный дубликат [Обнаружение неопределенного свойства объекта] (http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property) – cnorthfield

+0

Вы уверены 'weatherDate.weather [0] .description'? Если вы используете 'console.log (weatherDate),' что он показывает? –

+2

Вы использовали отладчик (или даже консольный журнал), чтобы убедиться, что 'weatherDate' содержит значения, которые вы * думаете * он держит? Вы должны убедиться, что вы публикуете фактическое значение, возвращаемое вызовом ajax. Вы * код * может быть прав, но ваши * данные * могут быть неправильными. –

ответ

0

Ваш код слишком доверяя, что все эти вызовы будут работать.

В моем случае, json от http://api.sypexgeo.net/json правильно находит меня, но http://api.openweathermap.org/data/2.5/weather?" не имеет понятия об этом id города. Поэтому он передает обратно JSON, такие как:

{ 
    "cod": "404", 
    "message": "Error: Not found city" 
} 

Это, очевидно, испытывает недостаток в массиве weather, поэтому JS бросает неопределенный.

Решение будет состоять в том, чтобы получить спецификации из погоды api (и местоположения, пока вы на ней), и убедитесь, что код ответа хорош. (Я догадался, что «200» - это хорошо. У меня никогда не было успеха).

$(document).ready(function() { 
 
    var cityId; 
 
    var city; 
 
    var unitsFormat = "metric"; 
 

 
    var getWeatherInfo = function() { 
 
    $.getJSON("http://api.sypexgeo.net/json") 
 
     .done(function(locationData) { 
 
     cityId = locationData.city.id; 
 
     cityName = locationData.country.iso; 
 

 
     $.getJSON("http://api.openweathermap.org/data/2.5/weather?", { 
 
      id: cityId, 
 
      units: unitsFormat, 
 
      APPID: '610ae7b6406da76bb34ad4bb95cc3673' 
 
      }) 
 
      .done(function(weatherDate) { 
 
      if (weatherDate.cod != "200") { 
 
       console.log(weatherDate); 
 
       console.log("Couldn't find the weather!!!"); 
 
       return; 
 
      } 
 
      $("#w-icon").attr("src", "http://openweathermap.org/img/w/" + weatherDate.weather[0].icon + ".png"); 
 
      $("#temp").text(Math.round(weatherDate.main.temp) + "°C"); 
 
      $("#city").text(weatherDate.name + ","); 
 
      $("#country").text(cityName); 
 
      $("#description").text(weatherDate.weather[0].description); 
 

 
      }); 
 
     }); 
 
    } 
 

 
    getWeatherInfo(); 
 

 
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
 
     "http://www.w3.org/TR/html4/loose.dtd"> 
 
<html> 
 

 
<head> 
 
    <meta charset="UTF-8"> 
 
    <title>FreeCodeCamp - Local Weather</title> 
 
    <script src="//code.jquery.com/jquery-3.0.0.js"></script> 
 
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> 
 
    <link rel="stylesheet" type="text/css" href="style.css" /> 
 
</head> 
 

 
<body> 
 
    <div id="main" class="text-center container"> 
 
    <h1>FreeCodeCamp - Weather App</h1> 
 
    <div class="row" id="fade"> 
 
     <div style="margin-top: 200px;"> 
 
     <span id="city"></span> 
 
     <span id="country"></span> 
 
     <div id="weather"> 
 
      <img id="w-icon"><span id="temp"></span> 
 
     </div> 
 
     <span id="description"></span> 
 
     </div> 
 
    </div> 
 
    <div id="author"> 
 
     <span> Created by Kaan Karaca</span> 
 
     <br> 
 
     <span><a href="http://github.com/h4yfans">@GitHub</a> </span> 
 
     <br> 
 
     <span><a href="https://www.freecodecamp.com/h4yfans">@FreeCodeCamp</a> </span> 
 
    </div> 
 

 
    </div> 
 
</body> 
 

 
</html>

+0

Код, поскольку он действительно работает для меня, я думаю, что проблема с плохой загрузкой библиотеки jquery, ошибка действительно в том, что DOM не определена для скрипта – iomv

+0

3 часа назад работал API. Теперь тот же код и не работает. http://openweathermap.org/current Я использовал этот API. –

+0

Если проблема была в ответе на код ошибки, тогда на 'weatherDate.main.temp' будет ошибка. Вы просто не передаете ключ API при выполнении запроса. –

Смежные вопросы