La interfaz Fetch API permite que el navegador web realice solicitudes HTTP a servidores web.
😀 Ya no es necesario XMLHttpRequest.
Los números de la tabla especifican las primeras versiones del navegador que son totalmente compatibles con Fetch API:
Chrome 42 | Edge 14 | Firefox 40 | Safari 10.1 | Opera 29 |
Apr 2015 | Aug 2016 | Aug 2015 | Mar 2017 | Apr 2015 |
El siguiente ejemplo recupera un archivo y muestra el contenido:
fetch(file)
.then(x => x.text())
.then(y => myDisplay(y));
Pruébelo usted mismo →
<!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>
Dado que Fetch se basa en async y await, el ejemplo anterior podría ser más fácil de entender así:
async function getText(file) {
let x = await fetch(file);
let y = await x.text();
myDisplay(y);
}
Pruébelo usted mismo →
<!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>
O incluso mejor: utilice nombres comprensibles en lugar de x e y:
async function getText(file) {
let myObject = await fetch(file);
let myText = await myObject.text();
myDisplay(myText);
}
Pruébelo usted mismo →
<!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>