[英]JavaScript requesting JSON info. returns incorrect result
我對JavaScript很陌生,並且在導入JSON時一直遇到問題。 我正在做與鋼鐵俠中看到的警報類似的事情,賈維斯向他打招呼。 當我嘗試通過OpenWeatherMap API導入天氣時,會得到隨機的結果,例如溫度為0 ...我只需要定義4個變量,一個與溫度有關,一個與風速有關,一個與一般說明(data.weather.main)
,然后再加上濕度。 如果有人可以告訴我我做錯了什么,和/或向我展示如何針對其中一個變量進行操作的示例,我將不勝感激。 提前致謝
JSON:
{ "coord": { "lon": -71.37, "lat": 42.24 }, "weather": [{ "id": 802, "main": "Clouds", "description": "scattered clouds", "icon": "03n" }], "base": "stations", "main": { "temp": 63.55, "pressure": 1014, "humidity": 77, "temp_min": 62.6, "temp_max": 66.2 }, "visibility": 16093, "wind": { "speed": 4.7, "deg": 80 }, "clouds": { "all": 40 }, "dt": 1500871860, "sys": { "type": 1, "id": 2390, "message": 0.0161, "country": "US", "sunrise": 1500888653, "sunset": 1500941553 }, "id": 4950790, "name": "Sherborn", "cod": 200 }
碼:
<html>
<title>Good Morning</title>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<script src="http://code.responsivevoice.org/responsivevoice.js"></script>
<script>
/*
function setup() {
$.getJSON('http://api.openweathermap.org/data/2.5/weather?q={Sherborn}&APPID=355c20fb396a58c1c25e0c341c9035ed&units=imperial', function(Data) {
console.log (Data.weather.main);
if (Data.weather.main = 'Clouds') {
window.WeatherStatus = "Cloudy"
}})} */
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q={Sherborn}&APPID=355c20fb396a58c1c25e0c341c9035ed&units=imperial',
datatype: 'json',
type: 'get',
cache: false,
success: function(Data) {
$(Data.main).each(function(temp, wind) {
console.log(temp);
console.log(wind)
});
}
});
</script>
</body>
</html>
將您的退貨成功更改為:
success: function(Data) {
console.log(Data.weather[0].main);//show weather
console.log(Data.main.temp);//show temp
console.log(Data.main.humidity);//show humidity
console.log(Data.wind.speed);//show speed
}
在AJAX返回成功后,請執行
console.log(Data.main.temp);
//和
console.log(Data.wind.speed);
您應該看到正確的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.