我正在訪問OpenWeather數據使用他們的API,並沒有成功地得到它的工作。我認爲我錯誤地訪問了JSON,但沒有破解它。OpenWeather JSONP
我使用下面的代碼JSFiddle here)查詢自己的數據:
function getWeather(lat, lon, callback) {
var weather = 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&cnt=1';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
};
我跑回到本查詢
{
"coord":
{
"lon":-6.27,"lat":13.34
},
"sys":
{
"message":0.0088,
"country":"ML",
"sunrise":1390719134,
"sunset":1390760592
},
"weather":
[
{
"id":800,"main":"Clear",
"description":"Sky is Clear",
"icon":"01n"
}
],
"base":"cmc stations",
"main":
{"temp":293.154,
"temp_min":293.154,
"temp_max":293.154,
"pressure":989.21,
"sea_level":1024.43,
"grnd_level":989.21,
"humidity":64
},
"wind":
{
"speed":4.1,
"deg":52.0018
},
"clouds":
{
"all":0
},
"dt":1390695239,
"id":2451478,
"name":"Segou",
"cod":200
}
我再試圖格式化這樣的迴應:
var lat = 13.3428;
var lon = -6.26612;
getWeather(lat, lon, function (data) {
var tempHTML = "";
tempHTML = tempHTML + '<h3>WEATHER INFO:</h3>';
tempHTML = tempHTML + 'Weather data received <br/>';
tempHTML = tempHTML + '<h3>WEATHER:</h3>';
tempHTML = tempHTML + 'Weather Id: ' + data.weather[0].id + '<br/>';
tempHTML = tempHTML + 'Weather Main: ' + data.weather[0].main + '<br/>';
tempHTML = tempHTML + 'Weather Description: ' + data.weather[0].description + '<br/>';
tempHTML = tempHTML + 'Weather Icon: ' + data.weather[0].icon + '<br/>';
tempHTML = tempHTML + '<h3>MAIN:</h3>';
tempHTML = tempHTML + 'Temperature: ' + data.main[0].temp + 'degrees<br/>';
tempHTML = tempHTML + 'Temperature Min: ' + data.main[0].temp_min + 'degrees<br/>';
tempHTML = tempHTML + 'Temperature Max: ' + data.main[0].temp_max + 'degrees<br/>';
tempHTML = tempHTML + 'Pressure: ' + data.main[0].pressure + 'Kpa<br/>';
tempHTML = tempHTML + 'Humidity: ' + data.main[0].humidity + '%<br/>';
tempHTML = tempHTML + '<h3>WIND:</h3>';
tempHTML = tempHTML + 'Wind Speed: ' + data.wind[0].speed + 'kmh<br/>';
tempHTML = tempHTML + 'Wind Direction: ' + data.wind[0].deg + 'degrees <br/>';
tempHTML = tempHTML + '<h3>CLOUDS:</h3>';
tempHTML = tempHTML + 'Cloud Coverage: ' + data.clouds[0].all + '%<br/>';
document.getElementById('weather_output').innerHTM = tempHTML;
});
如果你看我的JSFiddle我得到一個控制檯錯誤:一個對象,而不是一個數組,因此使用[0]
Uncaught SyntaxError: Unexpected token : api.openweathermap.org/data/2.5/weather?lat=13.3428&lon=-6.26612&cnt=1&callback=jQuery191009959305939264596_1390699334749&_=1390699334750:1
Uncaught TypeError: Cannot read property 'temp' of undefined (index):36
您還在錯誤地訪問某些屬性。例如,你應該訪問'data.sys.country'而不是'data.sys [0] .country'。你在你的代碼中這樣做。 –
[It does,@FelixKling](http://api.openweathermap.org/data/2.5/weather?q=London,uk&callback=jsonp)。 – Andy
@Andy:Mmh,那麼錯誤消息'Uncaught SyntaxError:Unexpected token:'沒有意義或者不相關。 *編輯:*嗯,它並沒有在我第一次在Chrome中加載小提琴時發出JSOP請求,但是當我再次運行它時,它確實很奇怪。無論如何,我會刪除我的第一條評論。 –