fetch api
We all remember the dreaded XMLHttpRequest we used back in the day to make requests, it involved some really messy code, it didn't give us promises and let's just be honest, it wasn't pretty JavaScript, right? Maybe if you were using jQuery, you used the cleaner syntax with jQuery.ajax()
.
我们所有人都记得我们在过去用于发出请求的可怕的XMLHttpRequest,它涉及一些非常凌乱的代码,它没有给我们承诺,老实说,它不是漂亮JavaScript,对吧? 也许如果您使用的是jQuery,则可以使用带有jQuery.ajax()
的更jQuery.ajax()
语法。
Well JavaScript has it's own built-in clean way now. Along comes the Fetch API a new standard to make server request jam-packed with promises and all those things we learned to love over the years.
好吧,JavaScript现在拥有自己的内置清理方式。 随着Fetch API的出现,新的标准使服务器请求充满了承诺以及多年来我们学到的所有东西。
我们如何使用Fetch API? ( How do we use the Fetch API? )
In a very simple manner all you really do is call fetch with the URL you want, by default the Fetch API uses the GET method, so a very simple call would be like this:
以一种非常简单的方式,您真正要做的就是使用所需的URL调用fetch,默认情况下,Fetch API使用GET方法,因此,一个非常简单的调用将如下所示:
fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function() {
// Your code for handling the data you get from the API
})
.catch(function() {
// This is where you run code if the server returns any errors
});
Looks pretty simple right? So let's starting using it...
看起来很简单吧? 因此,让我们开始使用它...
使用提取从API获取数据 (Using fetch to get data from an API)
We are now going to build a simple GET request, in this case, I will use the Random User API and we will get 10 users and show them on the page using vanilla JavaScript.
现在,我们将构建一个简单的GET请求,在这种情况下,我将使用Random User API ,我们将获得10个用户,并使用普通JavaScript将其显示在页面上。
Let's get started with the HTML, all we really need is a heading and an unordered list:
让我们开始使用HTML,我们真正需要的只是一个标题和一个无序列表:
<h1>Authors</h1>
<ul id="authors"></ul>
The idea is to get all the data from the Random User API and display it in list items inside the author's list.
这个想法是从Random User API获取所有数据,并将其显示在作者列表内的列表项中。
The first step is to actually set the URL we need and also the list we are gonna put the data in, so in the Javascript we write:
第一步是实际设置我们需要的URL以及要放入数据的列表,因此在Javascript中我们编写:
const ul = document.getElementById('autho