簡體   English   中英

JSON請求對象未定義

[英]Json request object is undefined

所以我試圖從開放天氣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(); }); 

$.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> 

您打錯很簡單。

您正在使用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);
  })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM