JavaScript Fetch API
The Fetch API helps web browsers ask web servers for information through HTTP requests.
😀 You don't have to use XMLHttpRequest anymore.
A Fetch API Example
The code snippet provided retrieves a file and shows its contents.
Because Fetch relies on async and await, the example provided might be simpler to comprehend in this manner:
Or, it's even better to use clear names instead of 'x' and 'y'.
<!DOCTYPE html>
<html>
<body>
<p id="demo">Fetch a file to change this text.</p>
<script>
let file = "/fetch_info.txt"
fetch(file).then(x => x.text()).then(y => document.getElementById("demo").innerHTML = y);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="demo">Fetch a file to change this text.</p>
<script>
getText("/fetch_info.txt");
async function getText(file) {
let x = await fetch(file);
let y = await x.text();
document.getElementById("demo").innerHTML = y;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="demo">Fetch a file to change this text.</p>
<script>
getText("/fetch_info.txt");
async function getText(file) {
let myObject = await fetch(file);
let myText = await myObject.text();
document.getElementById("demo").innerHTML = myText;
}
</script>
</body>
</html>