XMLHttpRequest を使用して、Web ページの気象サービス API からコンテンツを更新しようとしています。
残念ながら、私はこの JavaScript 機能を初めて使用します。Mozilla のドキュメントに目を通しましたが、ウェブページの API から情報を更新する方法について、まだ少し混乱しています。
リフレッシュ機能とaddWeather機能を含む私のJavascript。更新機能は、私のウェブサイトの API 情報を 1 時間ごとに更新することを想定しています (これは、ヘルプが必要な xmlhttprequest を利用します)。addWeather 関数は API 情報を html に追加し、実際にうまく機能します。
Javascript は次のとおりです。
window.onload = init;
function init() {
//populate the weather
addWeather();
//refresh the page every hour
setInterval(refreshPage(), 3600000);
}
//refresh the page information every hour
function refreshPage(){
//make new request to the webservice
var req = new XMLHttpRequest();
req.onload = addWeather();
}
//add the weather info from the weather service
function addWeather(){
jQuery(document).ready(function($) {
$.ajax({
url: "http://api.wunderground.com/api/6368023a57d122c7/geolookup/conditions/q/DominicanRepublic/Barahona.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp = parsed_json['current_observation']['temp_c'];
var weather = parsed_json['current_observation']['weather'];
var humid = parsed_json['current_observation']['relative_humidity'];
var wind_direction = parsed_json['current_observation']['wind_dir'];
var wind_speed = parsed_json['current_observation']['wind_kph'];
var wind_string = wind_direction + " " + wind_speed + " Km/h";
document.getElementById("weather").innerHTML = "Weather " + weather;
document.getElementById("temp").innerHTML = "Tempurature " + temp + "°C";
document.getElementById("hum").innerHTML = "Humidity " + humid;
document.getElementById("wind").innerHTML = "Wind " + wind_string;
}
});
});
}