四種在 JavaScript 中進(jìn)行 API 調(diào)用的方法
在 JavaScript 中,有多種調(diào)用 API 的方法,以下是一些常用的方法和技巧:
1. XMLHttpRequest
這是 JavaScript 中的一個(gè)內(nèi)置對(duì)象,允許發(fā)出異步 HTTP 請(qǐng)求。這是在 JavaScript 中進(jìn)行 API 調(diào)用的傳統(tǒng)方式。但是,它有一個(gè)復(fù)雜的 API,并且經(jīng)常被更現(xiàn)代的方法所取代。
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();
默認(rèn)情況下,我們會(huì)收到字符串格式的響應(yīng)。我們需要將其解析為 JSON。
通過(guò)引入 fetch,XMLHttpRequest 在 ES 6 中被棄用。但是當(dāng)您需要使用舊瀏覽器并且不想使用 polyfill 時(shí),XMLHttpRequest 仍然很有用。
2. Fetch API
這是一個(gè)更新更強(qiáng)大的 API,用于進(jìn)行 API 調(diào)用。它提供了一種更簡(jiǎn)單、更靈活的方式來(lái)處理請(qǐng)求和響應(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 非常強(qiáng)大,我們可以使用瀏覽器獲取 API 輕松發(fā)送 AJAX 請(qǐng)求。
3. Axios
Axios 是一個(gè)流行的第三方庫(kù),用于在 JavaScript 中發(fā)出 HTTP 請(qǐng)求。它同時(shí)支持瀏覽器和 Node.js 環(huán)境,并提供簡(jiǎn)單而優(yōu)雅的 API。
axios的安裝方法。
npm install axios
包含 Axios 的最簡(jiǎn)單方法是在 HTML 文件中使用外部 CDN。
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Axios 具有以下優(yōu)點(diǎn):
- Axios 執(zhí)行自動(dòng)轉(zhuǎn)換并以 JSON 格式返回?cái)?shù)據(jù)。
- 更好的處理錯(cuò)誤。
- 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 庫(kù),則可以使用其 AJAX 方法進(jìn)行 API 調(diào)用。它簡(jiǎn)化了流程并提供了其他功能,例如 JSONP 支持。
JQuery 有很多方法來(lái)處理異步 HTTP 請(qǐng)求。為了使用 jQuery,我們需要包含 jQuery 的源文件。$.ajax() 方法用于發(fā)出 HTTP 請(qǐng)求。
查詢內(nèi)容分發(fā)網(wǎng)絡(luò):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<!DOCTYPE html>
<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ù),一些是必需的,另一些是可選的。它包含兩個(gè)回調(diào)函數(shù) success 和 error 來(lái)處理收到的響應(yīng)。
結(jié)論
這些是在 JavaScript 中進(jìn)行 API 調(diào)用的一些常見(jiàn)方法。每種方法都有其優(yōu)點(diǎn),在具體工作中,請(qǐng)選擇合適的方法進(jìn)行使用。
大多數(shù)實(shí)時(shí)應(yīng)用程序使用 Axios 來(lái)發(fā)出 HTTP 請(qǐng)求。Axios 非常易于使用,是一個(gè)用于發(fā)出 HTTP 請(qǐng)求的開(kāi)源庫(kù)。這些是發(fā)出 HTTP 請(qǐng)求的最流行的方式。