I'm learning to use XMLHttp to fetch information, and I can't figure out the scope within the functions. This is my code:
<p id="demo">
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
results = this.responseText;
document.getElementById("demo").innerHTML = results;
}
};
xhttp.open("GET", "my_file.txt", true);
xhttp.send();
</script>
It populates "demo"'s innerHTML correctly, but I'm trying to get the contents of "results" available outside the callback function. Nothing I've tried so far has worked. I've tried declaring it just above the XMLHttp declaration, thinking it would be global, but's not. I've even tried setting the innerHTML of p and then setting "results" with the innerHTML of "demo". Nothing works. I just can't get my head wrapped around the scoping rules.