初学者数据获取指南(AJAX、Fetch API 和 Async/Await)
介绍
在本教程中,我将解释如何使用 AJAX、Fetch API 和 Async/Await 等 Web 技术从外部 API 异步获取数据。
如何从外部 API 获取数据
AJAX
AJAX 代表异步 Javascript 和 XML,它是一组从客户端或服务器异步发送和接收数据的 Web 技术,它是在后台完成的,您无需重新加载网页,JSON(Javascript 对象表示法)实际上已经取代了 XML(可扩展标记语言),大多数 API 返回 JSON 数据,AJAX 也可以返回纯文本。
以下是 AJAX 工作原理的描述
通过 AJAX 调用发送请求
,JSON 格式的数据从服务器异步获取,页面内容无需重新加载即可更新。我们可以从本地机器或服务器(公共 API)获取数据。 我将在下面的代码中演示如何使用 AJAX 从Github API(一个外部 API)获取数据。
//Create the XHR Object
let xhr = new XMLHttpRequest;
//Call the open function, GET-type of request, url, true-asynchronous
xhr.open('GET', 'https://api.github.com/users', true)
//call the onload
xhr.onload = function()
{
//check if the status is 200(means everything is okay)
if (this.status === 200)
{
//return server response as an object with JSON.parse
console.log(JSON.parse(this.responseText));
}
}
//call send
xhr.send();
//Common Types of HTTP Statuses
// 200: OK
// 404: ERROR
// 403: FORBIDDEN
获取 API
它是处理HTTPRequest的最新标准,它是窗口对象的一部分,我们也可以轻松地从外部 API 获取数据。Fetch 返回Promises
我将在下面的代码中演示如何使用 Fetch API 从Github API(一个外部 API)获取数据。
//call the fetch function
fetch('https://api.github.com/users')
.then(res => res.json())//response type
.then(data => console.log(data)); //log the data;
异步/等待
它是 ES7 标准的一部分,现在已在 Chrome 中完全实现,我们向函数添加 async ,它返回一个Promise。
我将在下面的代码中演示如何从Github API(一个带有 Async/Await 的外部 API)获取数据。
async function getData()
{
//await the response of the fetch call
let response = await fetch('https://api.github.com/users');
//proceed once the first promise is resolved.
let data = await response.json()
//proceed only when the second promise is resolved
return data;
}
//call getData function
getData()
.then(data => console.log(data));//log the data
笔记
这三种方法都可以用于获取数据,我其实更喜欢使用 Fetch API。除了这三种方法之外,还有其他几种方法(axios、superagent 等),本文不做讨论。这些 API 各有不同,请求的接收方式和响应的提供方式也各有不同。外部 API 的文档可以为您提供指导。
希望您喜欢本教程,感谢您的阅读。