Got a server that hosts a website and collects data. Though it is actually Energy/power data in home automation, I will make the question more clear with name:age pairs:
Suppose I have a Json object/array with names and ages. e.g
[{“name”:”John”, “age”: 15},{“name”:”Alice”, “age”: 29},{“name”:”Pete”, “age”: 85}…. ]
I will get that string via an AJAX call in javascript. I’d like to update the website values accordingly every -say- 20secs.
My current approach is a series of if statements, as the order in which the json string array is sent is not yet fixed:
<script>
setInterval(function ( ) {
var xmlhttp_indexdata = new XMLHttpRequest();
xmlhttp_indexdata.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
const json_indexdata = JSON.parse(xmlhttp_indexdata.responseText);
for (const x in json_indexdata) {
if (json_indexdata[x].name == "Pete"){
document.getElementById("Petesage").innerHTML = json_indexdata[x].age;
}
if (json_indexdata[x].name == "Angela") {
document.getElementById("Angelasage").innerHTML = json_indexdata[x].age;
}
if (json_indexdata[x].name == "Alice") {
document.getElementById("Alicesage").innerHTML = json_indexdata[x].age;
}
.... etc
};
xmlhttp_indexdata.open("GET", "/get_indexdata", true);
xmlhttp_indexdata.send();
}, 20000 ) ;
</script>
I tried the code as depicted above. it works, but is there a more elegant way?