JavaScript ดึงข้อมูล API


สารบัญ

    แสดงสารบัญ

อินเทอร์เฟซ Fetch API ช่วยให้เว็บเบราว์เซอร์ส่งคำขอ 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

ตัวอย่าง Fetch 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>

เนื่องจากการดึงข้อมูลจะขึ้นอยู่กับอะซิงก์และรอ ตัวอย่างด้านบนจึงอาจเข้าใจได้ง่ายกว่าดังนี้:

ตัวอย่าง

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>