เว็บ API


สารบัญ

    แสดงสารบัญ

Web API เป็นความฝันของนักพัฒนา

  • มันสามารถขยายการทำงานของเบราว์เซอร์ได้

  • สามารถลดความซับซ้อนของฟังก์ชันที่ซับซ้อนได้อย่างมาก

  • สามารถจัดเตรียมไวยากรณ์ที่ง่ายให้กับโค้ดที่ซับซ้อนได้

เว็บ API คืออะไร?

API ย่อมาจาก Application Programming Iinterface

Web API คืออินเทอร์เฟซการเขียนโปรแกรมแอปพลิเคชันสำหรับเว็บ

Browser API สามารถขยายฟังก์ชันการทำงานของเว็บเบราว์เซอร์ได้

Server API สามารถขยายฟังก์ชันการทำงานของเว็บเซิร์ฟเวอร์ได้


API ของเบราว์เซอร์

เบราว์เซอร์ทั้งหมดมีชุด Web API ในตัว เพื่อรองรับการดำเนินงานที่ซับซ้อน และเพื่อช่วยในการเข้าถึงข้อมูล

ตัวอย่างเช่น Geolocation API สามารถส่งคืนพิกัดของตำแหน่งของเบราว์เซอร์ได้

ตัวอย่าง

รับละติจูดและลองจิจูดของตำแหน่งของผู้ใช้:

const myElement = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    myElement.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  myElement.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude; 
}

ลองด้วยตัวคุณเอง →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Geolocation</h2>

<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>
const x = document.getElementById("demo");

function getLocation() {
  try {
    navigator.geolocation.getCurrentPosition(showPosition);
  } catch {
    x.innerHTML = err;
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;
}
</script>

</body>
</html>


API ของบุคคลที่สาม

API ของบุคคลที่สามไม่ได้ถูกสร้างขึ้นในเบราว์เซอร์ของคุณ

หากต้องการใช้ API เหล่านี้ คุณจะต้องดาวน์โหลดโค้ดจากเว็บ

ตัวอย่าง:

  • YouTube API - ช่วยให้คุณสามารถแสดงวิดีโอบนเว็บไซต์

  • Twitter API - ให้คุณแสดงทวีตบนเว็บไซต์

  • Facebook API - ช่วยให้คุณแสดงข้อมูล Facebook บนเว็บไซต์