JavaScript 进行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://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 方法有很多参数,一些是必需的,另一些是可选的。它包含两个回调函数 success 和 error 来处理收到的响应。
结论
这些是在 JavaScript 中进行 API 调用的一些常见方法。每种方法都有其优点,在具体工作中,请选择合适的方法进行使用。
大多数实时应用程序使用 Axios 来发出 HTTP 请求。Axios 非常易于使用,是一个用于发出 HTTP 请求的开源库。这些是发出 HTTP 请求的最流行的方式。






