I have code that I would like to return straight text, that has been read from a text file (happens to be JSON in this instance, but may not always be in future) and I would just like to pass the results back from a function call. The text, or sections thereof will eventually be displayed on the web page. See next bit of code...
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Not Working Example</title>
</head>
<body onload="myfunction()">
<div id="demo1" onclick="loadDoc()">demo1</div>
<div id="demo2" onclick="loadDoc()">demo2</div>
<div id="demo3" onclick="loadDoc()">demo3</div>
<script>
var dataString = "Test";
function loadDoc() {
var string = readDoc("TestData.json");
document.getElementById("demo2").innerHTML = string;
document.getElementById("demo3").innerHTML = dataString;
}
function readDoc(fileName) {
var fReader = new XMLHttpRequest();
fReader.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
dataString = this.responseText;
document.getElementById("demo1").innerHTML = this.responseText;
}
};
fReader.open("GET", fileName, true);
fReader.send();
}
</script>
</body>
</html>
I am trying to create a function (readDoc) that simply returns a data string (see line 14), but I am having issues passing the responseText to either a global variable or a result back to the invokation on line 14 & line 22. What am I doing wrong? Unlike line 24, I don't want to write straight to an HTML element as I want to manipulate the data first (in a separate function), before displaying. The (temporarily simple) example of "TestData.json" is...
{
"DataValue": 33
}
I have tried lots of different permutations but can't seem to manage to get the desired result. Some 'genioid' out there is going to say "ahh, easy I can seem what the idiot has done wrong.", but I can't see the woods for the trees.