On my RPi I have an application (developed in C++) running in the background that does some complex mathematics based on some sensor input and produces some result every second. I want to display this data on a website. So I had the idea to have the application produce a JSON formatted file and read that interactively from a javascript script.
The app now produces a file ModelState.json
in my html directory that looks like
{ "x" : -0.886289 , "y" : -0.434931 }
Based on this answer, I wrote the following html/js
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p id="ModelState"></p>
</body>
<script type="text/javascript">
window.onload = function () {
setInterval(showModelState, 1000);
function showModelState() {
readJsonFile("ModelState.json", function(ModelStateJson){
var ModelStateObj = JSON.parse(ModelStateJson);
if (ModelStateObj.x && ModelStateObj.y) {
document.getElementById("ModelState").innerHTML =
"x: " + ModelStateObj.x + ", " +
"y: " + ModelStateObj.y;
}
});
}
function readJsonFile(file, callback) {
let rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status === 200) {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
}
</script>
</html>
However, what I observe is that the file seems to be loaded once. The data on the webpage doesn't change, while the data in the file does change.
I don't know why. Is it that the XMLHttpRequest
keeps the file open, such that onreadystatechange
is not triggered and the callback function is not called again? I would expect the send
response to finish the request, thus close the file.