首頁  >  文章  >  web前端  >  您是否嘗試過 JavaScript 中的所有 API 呼叫?這裡有一些方法可以做到這一點

您是否嘗試過 JavaScript 中的所有 API 呼叫?這裡有一些方法可以做到這一點

PHPz
PHPz原創
2024-07-18 08:03:09508瀏覽

Have you tried all API calls in JavaScript? Here are ays to do it

API 呼叫是現代 Web 開發的關鍵部分。 JavaScript 提供了多種方法來完成此任務,每種方法都有自己的優點和缺點。本文將向您介紹在 JavaScript 中進行 API 呼叫的四種主要方法,您可以在專案中使用它們。

XMLHttp請求(XHR)

XMLHttpRequest (XHR) 是呼叫 API 的傳統方式,所有瀏覽器版本都支援。此方法可靠且廣泛使用,儘管其語法有時難以閱讀和維護。

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            console.log(JSON.parse(xhr.responseText)); // Parse and log the response data
        } else {
            console.error('Error:', xhr.statusText); // Log any errors
        }
    }
};
xhr.send();

取得API

Fetch API 是一種基於承諾的更現代、更簡單的 API 呼叫方法。它支援非同步操作,並且很容易使用 async 和 await 進行擴展。

fetch("https://api.example.com/data")
    .then(response => response.json())
    .then(data => console.log(data)) // Log the response data
    .catch(error => console.error('Error:', error)); // Log any errors

使用非同步和等待。

async function fetchData() {
    try {
        const response = await fetch("https://api.example.com/data");
        const data = await response.json();
        console.log(data); // Log the response data
    } catch (error) {
        console.error('Error:', error); // Log any errors
    }
}
fetchData();

阿克西奧斯

Axios 是一個流行的 HTTP 請求庫,它提供了一個簡單且一致的介面來進行 API 呼叫。需要先使用npm或yarn安裝它。
npm 安裝 axios

紗線添加 axios

然後就可以使用Axios進行API呼叫了:

const axios = require('axios');

axios.get("https://api.example.com/data")
    .then(response => {
        console.log(response.data); // Log the response data
    })
    .catch(error => {
        console.error('Error:', error); // Log any errors
    });

使用非同步和等待:

async function fetchData() {
    try {
        const response = await axios.get("https://api.example.com/data");
        console.log(response.data); // Log the response data
    } catch (error) {
        console.error('Error:', error); // Log any errors
    }
}
fetchData();

jQuery AJAX

jQuery AJAX 是一種使用 jQuery 函式庫進行 API 呼叫的方法。雖然 jQuery 現在不太常用,但它仍然出現在較舊的專案中。

<!-- Include jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
$(document).ready(function() {
    $.ajax({
        url: "https://api.example.com/data",
        method: "GET",
        success: function(data) {
            console.log(data); // Log the response data
        },
        error: function(error) {
            console.error('Error:', error); // Log any errors
        }
    });
});
</script>

來源照片:
拉科齊、格雷格.網站設計書籍。在線的。在:不飛濺。 2016。可從:https://unsplash.com/photos/html-css-book-vw3Ahg4x1tY。 [引用。 2024-07-16].

以上是您是否嘗試過 JavaScript 中的所有 API 呼叫?這裡有一些方法可以做到這一點的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn