JavaScript 获取 API


目录

    显示目录

Fetch API 接口允许 Web 浏览器向 Web 服务器发出 HTTP 请求。

😀 不再需要 XMLHttpRequest 了。

浏览器支持

表中的数字指定了完全支持 Fetch API 的第一个浏览器版本:


Chrome 42 Edge 14 Firefox 40 Safari 10.1 Opera 29
Apr 2015 Aug 2016 Aug 2015 Mar 2017 Apr 2015

获取 API 示例

下面的示例获取文件并显示内容:

例子

fetch(file)
.then(x => x.text())
.then(y => myDisplay(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>

由于 Fetch 是基于 async 和 await 的,所以上面的例子可能更容易理解,如下所示:

例子

async function getText(file) {
  let x = await fetch(file);
  let y = await x.text();
  myDisplay(y);
}

自己尝试一下 →

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

或者甚至更好:使用易于理解的名称而不是 x 和 y:

例子

async function getText(file) {
  let myObject = await fetch(file);
  let myText = await myObject.text();
  myDisplay(myText);
}

自己尝试一下 →

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