AJAX (Asynchronous JavaScript and XML) is a technique for creating fast and dynamic web pages.
Web server sends only the structure of the page to client.
Web client runs JavaScript to request/submit data from/to different sources and modify webpage elements without reloading the page.
Temperature: <span id="temperature"></span><p>
Humidity: <span id="humidity"></span>
<script>
function loadDoc() {
// url of gov weather data
var url = "https://data.weather.gov.hk/weatherAPI/opendata/weather.php?dataType=rhrread&lang=en";
// create a new XMLHttpRequest object
var xhttp = new XMLHttpRequest();
// function to be called when the request is completed
xhttp.onreadystatechange = function() {
// check if the request is completed and the response is ready (code 200)
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
// display the temperature
document.getElementById("temperature").innerHTML = data.temperature.data[1].value;
// display the rainfall
document.getElementById("humidity").innerHTML = data.humidity.data[0].value;
}
};
// open a new request
xhttp.open("GET", url, true);
// send the request
xhttp.send();
}
// call the function to load the data
loadDoc();
</script>