Json请求对象未定义

时间:2015-08-06 22:14:18

标签: javascript json

所以我试图从开放天气api示例中获取json请求。但出于某种原因,当我去调用$ .each方法中的键值时,它表示键的值是未定义的。你们可以看看代码,看看它缺少什么?



function getGs(data) {
  $.each(data.main,function(i,wather){
    console.log(weather.humidity);
  })
}

$(document).ready(function() {
  var bggAPI = "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139?";

  $.ajax({
    dataType: "json",
    url: bggAPI
  });
  
  getGs();
  
});




2 个答案:

答案 0 :(得分:2)

$.ajax执行异步请求 成功完成后,success会被触发,您错过了它。

data.main不是数组,而是对象 data.weather是一个数组。

function getGs(data) {
  console.log(data.main.humidity);
  $.each(data.weather,function(i, weather) {
    console.log(weather.main);
  })
}

$(document).ready(function() {
  var bggAPI = "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139?";

  $.ajax({
    dataType: "json",
    url: bggAPI,
    success:getGs
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

你输错了很简单。

您使用wather作为参数,但在函数内调用weather

修改

在你给定的json中:

{ coord: { lon: 138.93, lat: 34.97 }, weather: [ { id: 800, main: "Clear", description: "Sky is Clear", icon: "01n" } ], base: "cmc stations", main: { temp: 300.37, pressure: 1015, humidity: 82, temp_min: 300.37, temp_max: 300.37 }, wind: { speed: 0.51, deg: 314, gust: 1.03 }, clouds: { all: 0 }, dt: 1438897427, sys: { type: 3, id: 10294, message: 0.0102, country: "JP", sunrise: 1438804655, sunset: 1438854132 }, id: 1851632, name: "Shuzenji", cod: 200 }

你有一个weather数组,但是你循环遍历主asvarray,而它只是天气数组中的一个属性,你的代码应该是:

$.each(data.weather,function(i,weather){
  console.log(weather.main);
  })
}