Currently, I am working on the MDN tutorial about 'XMLHttpRequest'. Unfortunately, when trying to use request.open('GET', url)
with a txt
file from my local directory, it is returning undefined. I have checked both the url
and request
in the console log, and they appear to be correct. Below you can find my code along with the txt
file I am attempting to utilize for this project. I am using VS Code as an editor and running it through a live server on Port: 5500.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>Ajax starting point</title>
<style>
html,
pre {
font-family: sans-serif;
}
body {
width: 500px;
margin: 0 auto;
background-color: #ccc;
}
pre {
line-height: 1.5;
letter-spacing: 0.05rem;
padding: 1rem;
background-color: white;
}
label {
width: 200px;
margin-right: 33px;
}
select {
width: 350px;
padding: 5px;
}
</style>
<!--[if lt IE 9]>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<h1>Ajax starting point</h1>
<form>
<label for="verse-choose">Choose a verse</label>
<select id="verse-choose" name="verse-choose">
<option>Verse 1</option>
<option>Verse 2</option>
<option>Verse 3</option>
<option>Verse 4</option>
</select>
</form>
<h2>The Conqueror Worm, <em>Edgar Allen Poe, 1843</em></h2>
<pre>
</pre>
<script>
const verseChoose = document.querySelector('select');
const poemDisplay = document.querySelector('pre');
verseChoose.onchange = function() {
const verse = verseChoose.value;
updateDisplay(verse);
};
function updateDisplay(verse) {
verse = verse.replace(" ", "");
verse = verse.toLowerCase();
let url = verse + '.txt';
let request = new XMLHttpRequest();
console.log(url);
console.log(request);
request.open('GET', url);
console.log(request.open('GET', url))
request.responseType = 'text';
request.onload = function() {
poemDisplay.textContent = request.response;
request.send();
};
}
updateDisplay('Verse 1');
verseChoose.value = 'Verse 1';
</script>
</body>
</html>
verse1.txt (in local directory)
Lo! 'tis a gala night
Within the lonesome latter years!
An angel throng, bewinged, bedight
In veils, and drowned in tears,
Sit in a theatre, to see
A play of hopes and fears,
While the orchestra breathes fitfully
The music of the spheres.
Mimes, in the form of God on high,
Mutter and mumble low,
And hither and thither fly-
Mere puppets they, who come and go
At bidding of vast formless things
That shift the scenery to and fro,
Flapping from out their Condor wings
Invisible Woe!