在 JavaScript 中,有多種調用 API 的方法,以下是一些常用的方法和技巧:
(資料圖片)
在 JavaScript 中,有多種調用 API 的方法,以下是一些常用的方法和技巧:
1. XMLHttpRequest
這是 JavaScript 中的一個內置對象,允許發出異步 HTTP 請求。這是在 JavaScript 中進行 API 調用的傳統方式。但是,它有一個復雜的 API,并且經常被更現代的方法所取代。
var xhr = new XMLHttpRequest();xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { var response = JSON.parse(xhr.responseText); // Process the response data here }};xhr.send();
默認情況下,我們會收到字符串格式的響應。我們需要將其解析為 JSON。
通過引入 fetch,XMLHttpRequest 在 ES 6 中被棄用。但是當您需要使用舊瀏覽器并且不想使用 polyfill 時,XMLHttpRequest 仍然很有用。
2. Fetch API
這是一個更新更強大的 API,用于進行 API 調用。它提供了一種更簡單、更靈活的方式來處理請求和響應。
fetch("https://jsonplaceholder.typicode.com/posts") .then(function(response) { if (response.ok) { return response.json(); } throw new Error("Network response was not ok."); }) .then(function(data) { // Process the response data here }) .catch(function(error) { // Handle errors here });
fetch API 非常強大,我們可以使用瀏覽器獲取 API 輕松發送 AJAX 請求。
3. Axios
Axios 是一個流行的第三方庫,用于在 JavaScript 中發出 HTTP 請求。它同時支持瀏覽器和 Node.js 環境,并提供簡單而優雅的 API。
axios的安裝方法。
npm install axios
包含 Axios 的最簡單方法是在 HTML 文件中使用外部 CDN。
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Axios 具有以下優點:
Axios 執行自動轉換并以 JSON 格式返回數據。更好的處理錯誤。Axios 支持多種瀏覽器。axios.get("https://jsonplaceholder.typicode.com/posts") .then(function(response) { // Process the response data here }) .catch(function(error) { // Handle errors here });
4. jQuery AJAX
如果您使用的是 jQuery 庫,則可以使用其 AJAX 方法進行 API 調用。它簡化了流程并提供了其他功能,例如 JSONP 支持。
JQuery 有很多方法來處理異步 HTTP 請求。為了使用 jQuery,我們需要包含 jQuery 的源文件。$.ajax() 方法用于發出 HTTP 請求。
查詢內容分發網絡:
<script src="https://gapis.geekzu.org/ajax/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
Document <script src="https://gapis.geekzu.org/ajax/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script> $.ajax({ url: "https://jsonplaceholder.typicode.com/posts", method: "GET", success: function(response) { // Process the response data here }, error: function(jqXHR, textStatus, errorThrown) { // Handle errors here }});</script>
$.ajax 方法有很多參數,一些是必需的,另一些是可選的。它包含兩個回調函數 success 和 error 來處理收到的響應。
結論
這些是在 JavaScript 中進行 API 調用的一些常見方法。每種方法都有其優點,在具體工作中,請選擇合適的方法進行使用。
大多數實時應用程序使用 Axios 來發出 HTTP 請求。Axios 非常易于使用,是一個用于發出 HTTP 請求的開源庫。這些是發出 HTTP 請求的最流行的方式。
關鍵詞: