4 種在 JavaScript 中進行API調(diào)用的方法

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();
默認情況下,我們會收到字符串格式的響應(yīng)。我們需要將其解析為 JSON。
通過引入 fetch,XMLHttpRequest 在 ES 6 中被棄用。但是當您需要使用舊瀏覽器并且不想使用 polyfill 時,XMLHttpRequest 仍然很有用。
2. Fetch API
這是一個更新更強大的 API,用于進行 API 調(diào)用。它提供了一種更簡單、更靈活的方式來處理請求和響應(yīng)。
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 輕松發(fā)送 AJAX 請求。
3. Axios
Axios 是一個流行的第三方庫,用于在 JavaScript 中發(fā)出 HTTP 請求。它同時支持瀏覽器和 Node.js 環(huán)境,并提供簡單而優(yōu)雅的 API。
axios的安裝方法。
npm install axios包含 Axios 的最簡單方法是在 HTML 文件中使用外部 CDN。
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>Axios 具有以下優(yōu)點:
Axios 執(zhí)行自動轉(zhuǎn)換并以 JSON 格式返回數(shù)據(jù)。
更好的處理錯誤。
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 調(diào)用。它簡化了流程并提供了其他功能,例如 JSONP 支持。
JQuery 有很多方法來處理異步 HTTP 請求。為了使用 jQuery,我們需要包含 jQuery 的源文件。$.ajax() 方法用于發(fā)出 HTTP 請求。
查詢內(nèi)容分發(fā)網(wǎng)絡(luò):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script></head><body><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></body></html>
$.ajax 方法有很多參數(shù),一些是必需的,另一些是可選的。它包含兩個回調(diào)函數(shù) success 和 error 來處理收到的響應(yīng)。
結(jié)論
這些是在 JavaScript 中進行 API 調(diào)用的一些常見方法。每種方法都有其優(yōu)點,在具體工作中,請選擇合適的方法進行使用。
大多數(shù)實時應(yīng)用程序使用 Axios 來發(fā)出 HTTP 請求。Axios 非常易于使用,是一個用于發(fā)出 HTTP 請求的開源庫。這些是發(fā)出 HTTP 請求的最流行的方式。
學(xué)習(xí)更多技能
請點擊下方公眾號
![]()
