测验

JavaScript 中调用 API 的不同方法是什么?

主题
JavaScript网络
在GitHub上编辑

TL;DR

在 JavaScript 中,您可以使用多种方法调用 API。最常见的方法是 XMLHttpRequestfetch 和第三方库,如 AxiosXMLHttpRequest 是传统方法,但更冗长。fetch 是现代方法,返回 promise,使其更易于使用。Axios 是一个流行的第三方库,它简化了 API 调用并提供了附加功能。


JavaScript 中调用 API 的不同方法

XMLHttpRequest

XMLHttpRequest 是在 JavaScript 中调用 API 的传统方法。与现代方法相比,它更冗长,需要更多代码。

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();

Fetch API

fetch 是一种现代且更方便的调用 API 的方法。它返回一个 promise,使处理异步操作更容易。

fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => console.log(data))
.catch((error) =>
console.error('There was a problem with the fetch operation:', error),
);

Axios

Axios 是一个流行的第三方库,它简化了 API 调用。它提供了额外的功能,如拦截器、自动 JSON 转换等。

axios
.get('https://api.example.com/data')
.then((response) => console.log(response.data))
.catch((error) =>
console.error('There was a problem with the Axios request:', error),
);

jQuery AJAX

jQuery 还提供了一个 ajax 方法来调用 API。这种方法在现代开发中不太常见,但在一些遗留项目中仍然使用。

$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
success: function (data) {
console.log(data);
},
error: function (error) {
console.error('There was a problem with the jQuery AJAX request:', error);
},
});

延伸阅读

在GitHub上编辑