Web Fetch API

JS Tutorial

JS Version

JS Objects

JS Function

JS Classes

JS Async

JS HTML DOM

JS Browser BOM

JS Web API

JS AJAX

JS JSON

JS vs JQUERY

JS Graphics

Web Fetch API

The below example is used to fetch a file and shows the content.

Example

<!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>

Output

Fetch a file to change this text.

The Fetch API interface allows web browser to make HTTP requests to web servers.

If you use the XMLHttpRequest Object, Fetch can do the same in a simpler way.

Use understandable names instead of x and y:

Example

<!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>

Output

Fetch a file to change this text.

The Fetch API interface allows web browser to make HTTP requests to web servers.

If you use the XMLHttpRequest Object, Fetch can do the same in a simpler way.