Fetch API-gränssnittet tillåter webbläsare att göra HTTP-förfrågningar till webbservrar.
😀 Inget behov av XMLHttpRequest längre.
Siffrorna i tabellen anger de första webbläsarversionerna som fullt ut stöder Fetch API:
Chrome 42 | Edge 14 | Firefox 40 | Safari 10.1 | Opera 29 |
Apr 2015 | Aug 2016 | Aug 2015 | Mar 2017 | Apr 2015 |
Exemplet nedan hämtar en fil och visar innehållet:
fetch(file)
.then(x => x.text())
.then(y => myDisplay(y));
Prova själv →
<!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>
Eftersom Fetch är baserat på asynkron och vänta, kan exemplet ovan vara lättare att förstå så här:
async function getText(file) {
let x = await fetch(file);
let y = await x.text();
myDisplay(y);
}
Prova själv →
<!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>
Eller ännu bättre: Använd begripliga namn istället för x och y:
async function getText(file) {
let myObject = await fetch(file);
let myText = await myObject.text();
myDisplay(myText);
}
Prova själv →
<!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>