我試圖檢索和使用JavaScript和URL請求從一個JSON對象,顯示關於當前的天氣信息顯示JSON數據:從URL檢索和URL
http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805'
的數據是這樣的:
{
"data": {
"current_condition": [
{
"cloudcover": "75",
"humidity": "88",
"observation_time": "03:30 PM",
"precipMM": "2.7",
"pressure": "1008",
"temp_C": "12",
"temp_F": "54",
"visibility": "8",
"weatherCode": "302",
"weatherDesc": [
{
"value": "Moderate rain"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0018_cloudy_with_heavy_rain.png"
}
],
"winddir16Point": "SE",
"winddirDegree": "140",
"windspeedKmph": "17",
"windspeedMiles": "11"
}
],
"request": [
{
"query": "DE3",
"type": "Postcode"
}
],
"weather": [
{
"date": "2012-05-09",
"precipMM": "11.8",
"tempMaxC": "13",
"tempMaxF": "56",
"tempMinC": "12",
"tempMinF": "53",
"weatherCode": "266",
"weatherDesc": [
{
"value": "Light drizzle"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0017_cloudy_with_light_rain.png"
}
],
"winddir16Point": "SE",
"winddirDegree": "141",
"winddirection": "SE",
"windspeedKmph": "12",
"windspeedMiles": "7"
},
{
"date": "2012-05-10",
"precipMM": "11.1",
"tempMaxC": "18",
"tempMaxF": "64",
"tempMinC": "6",
"tempMinF": "43",
"weatherCode": "353",
"weatherDesc": [
{
"value": "Light rain shower"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0009_light_rain_showers.png"
}
],
"winddir16Point": "SSW",
"winddirDegree": "209",
"winddirection": "SSW",
"windspeedKmph": "30",
"windspeedMiles": "19"
}
]
}
}
我已經嘗試了幾個腳本來嘗試獲取數據並將其顯示在div中。第一個是這樣的:
$.ajax({
url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805"
dataType: 'json',
success: function(data) {
jQuery.each(data, function() {
alert("HELLO");
alert("Current Cloud Cover = " + this.data.current_condition.cloudcover);
alert("Current Humidity = " + this.data.current_condition.humidity);
});
}
});
第二個看起來像這樣:
var postcode = document.getElementById("address").value;
function getWeather(userName, count) {
$.getJSON(
'http://free.worldweatheronline.com/feed/weather.ashx?q' + postcode + '&format=json&num_of_days=2&key=ec9c2dc5ba201904120805',
{},
showWeather,
//'jsonp'
);
}
function showWeather(day) {
var str = '<ul>';
str += '<h2>Tweets from ' + postcode + '</h2>';
var i = 0;
$.each(day, function(index, value) {
if (i == count) return;
var dt = new Date(value.date);
str += '<p>';
str += value.temp_C; //gets "text" from JSON
str += '</p>';
str += '';
str += '';
i++;
});
}
我想從JSON URL的天氣信息,並顯示一些的信息在一個div中,任何人都可以解釋如何做到這一點是這兩個腳本不工作。
你能後的錯誤消息,如果有一個? (查看錯誤的最簡單方法是使用谷歌瀏覽器,右鍵單擊頁面,選擇「檢查元素」,然後單擊「控制檯」選項卡以調出JavaScript控制檯。)我懷疑你遇到了交叉站點腳本錯誤,因爲您正試圖從不同的域下載數據。我認爲你需要做一些服務器端的工作來實現這一點。 – 10flow
Thansk回覆,但是我的控制檯窗口沒有顯示。 – lnelson92
你的第一次嘗試是否會產生alert(「Hello」)? –