翻译正在进行中。

首先,我们将从一个高层次看看API - 它们是什么;他们如何工作;如何在代码中使用它们,以及它们是如何组织的。我们也将看看不同主要类别的API以及它们的用途。

预备知识 基本计算机知识,对于HTML和CSS的基本理解(见JavaScript 第一步创建JavaScript代码块JavaScript 对象入门)。
目标 熟悉API,他们可以做什么,以及如何在代码中使用它们。

什么是API?

应用程序接口(API)是以编程语言提供的结构,允许开发人员更容易地创建复杂的功能。它们抽象出更复杂的代码,并提供一些简单的语法来使用。

来看一个现实世界中的例子:想想您的房子、公寓或其他住宅的电力供应,如果您想在您的房子里使用一个设备,您只需把它插入到一个插座中;您并不会直接把它连接到电源上 - 这样做效率会非常低,而且如果您不是电工,这么做将是困难和危险的。

图片来自:Overloaded plug socket 提供这: The Clear Communication People于Flickr。

同样,比如说,编程来显示一些3D图形,使用以更高级语言编写的API(例如JavaScript或Python)将会比直接编写直接控制计算机的GPU或其他图形功能的低级代码(比如C或C++)来执行操作要容易得多。

注:详细说明请见API - Glossary

客户端JavaScript中的API

客户端JavaScript中有很多可用的API — 他们本身并不是JavaScript语言的一部分,却建立在JavaScript语言核心的顶部,为使用JavaScript代码提供额外的超强能力。他们通常分为两类:

  • 浏览器API内置于Web浏览器中,能从浏览器和电脑周边环境中提取数据,并用来做有用的复杂的事情 。例如Geolocation API提供了一些简单的JavaScript结构以获得位置数据,因此您可以在Google地图上标示您的位置。在后台,浏览器确实使用一些复杂的低级代码(例如C++)与设备的GPS硬件(或可以决定位置数据的任何设施)通信来获取位置数据并把这些数据返回给您的代码中使用浏览器环境;但是,这种复杂性通过API抽象出来,因而与您无关。
  • 第三方API缺省情况下不会内置于浏览器中,通常必须在Web中的某个地方获取代码和信息。例如Twitter API 使您能做一些显示最新推文这样的事情,它提供一系列特殊的结构,可以用来请求Twitter服务并返回特殊的信息。

 

 

 

JavaScript,API和其他JavaScript工具之间的关系

如上所述,我们讨论了什么是客户端JavaScript API,以及它们与JavaScript语言的关系。让我们回顾一下,使其更清晰,并提及其他JavaScript工具的适用位置:

  • JavaScript — 一种内置于浏览器的高级脚本语言,您可以用来实现Web页面/应用中的功能。注意JavaScript也可用于其他象Node这样的的编程环境。但现在您不必考虑这些。
  • 客户端API — 内置于浏览器的结构程序,位于JavaScript语言顶部,使您可以更容易的实现功能。
  • 第三方API — 置于第三方普通的结构程序(例如Twitter,Facebook),使您可以在自己的Web页面中使用那些平台的某些功能(例如在您的Web页面显示最新的Tweets)。
  • JavaScript库 — 通常是包含具有特定功能的一个或多个JavaScript文件,把这些文件关联到您的Web页以快速或授权编写常见的功能。例如包含jQuery和Mootools
  • JavaScript框架 — 从库开始的下一步,JavaScript框架视图把HTML、CSS、JavaScript和其他安装的技术打包在一起,然后用来从头编写一个完整的Web应用。

API可以做什么?

在主流浏览器中有大量的可用API,您可以在代码中做许多的事情,对此可以查看MDN API index page

常见浏览器API

特别地,您将使用的最常见的浏览器API类别(以及我们将更详细地介绍的)是:

  • 操作文档的API内置于浏览器中。最明显的例子是DOM(文档对象模型)API,它允许您操作HTML和CSS — 创建、移除以及修改HTML,动态地将新样式应用到您的页面,等等。每当您看到一个弹出窗口出现在一个页面上,或者显示一些新的内容时,这都是DOM的行为。 您可以在在Manipulating documents中找到关于这些类型的API的更多信息。
  • 从服务器获取数据的API 用于更新网页的一小部分是相当好用的。这个看似很小的细节能对网站的性能和行为产生巨大的影响 — 如果您只是更新一个股票列表或者一些可用的新故事而不需要从服务器重新加载整个页面将使网站或应用程序感觉更加敏感和“活泼”。使这成为可能的API包括XMLHttpRequestFetch API。您也可能会遇到描述这种技术的术语Ajax。您可以在Fetching data from the server找到关于类似的API的更多信息。
  • 用于绘制和操作图形的API目前已被浏览器广泛支持 — 最流行的是允许您以编程方式更新包含在HTML <canvas> 元素中的像素数据以创建2D和3D场景的CanvasWebGL。例如,您可以绘制矩形或圆形等形状,将图像导入到画布上,然后使用Canvas API对其应用滤镜(如棕褐色滤镜或灰度滤镜),或使用WebGL创建具有光照和纹理的复杂3D场景。这些API经常与用于创建动画循环的API(例如window.requestAnimationFrame())和其他API一起不断更新诸如动画和游戏之类的场景。
  • 音频和视频API例如HTMLMediaElementWeb Audio APIWebRTC允许您使用多媒体来做一些非常有趣的事情,比如创建用于播放音频和视频的自定义UI控件,显示字幕字幕和您的视频,从网络摄像机抓取视频,通过画布操纵(见上),或在网络会议中显示在别人的电脑上,或者添加效果到音轨(如增益,失真,平移等) 。
  • 设备API基本上是以对网络应用程序有用的方式操作和检索现代设备硬件中的数据的API。我们已经讨论过访问设备位置数据的地理定位API,因此您可以在地图上标注您的位置。其他示例还包括通过系统通知(参见Notifications API)或振动硬件(参见Vibration API)告诉用户Web应用程序有用的更新可用。
  • 客户端存储API在Web浏览器中的使用变得越来越普遍 - 如果您想创建一个应用程序来保存页面加载之间的状态,甚至让设备在处于脱机状态时可用,那么在客户端存储数据将会是非常有用的。例如使用Web Storage API的简单的键 - 值存储以及使用IndexedDB API的更复杂的表格数据存储。

常见第三方API

第三方API种类繁多; 下列是一些比较流行的你可能迟早会用到的第三方API:

  • The Twitter API, 允许您在您的网站上展示您最近的推文等。
  • The Google Maps API allows you to do all sorts of things with maps on your Web pages (funnily enough, it also powers Google Maps). This is now an entire suite of API, which handle a wide variety of tasks, as evidenced by the Google Maps API Picker.
  • The Facebook suite of API enables you to use various parts of the Facebook ecosystem to benefit your app, for example by providing app login using Facebook login, accepting in-app payments, rolling out targetted ad campaigns, etc.
  • The YouTube API, which allows you to embed YouTube videos on your site, search YouTube, build playlists, and more.
  • The Twilio API, which provides a framework for building voice and video call functionality into your app, sending SMS/MMS from your apps, and more.

: 你可以在 Programmable Web API directory.上发现更多关于第三方API的信息。

API如何工作?

Different JavaScript API work in slightly different ways, but generally they have common features and similar themes to how they work.

它们是基于对象的

API are interacted with in your code using one of more JavaScript objects, which serve as containers for the data the API uses (contained in object properties), and the functionality the API makes available (contained in object methods).

Note: If you are not already familiar with how objects work, you should go back and work through our JavaScript objects module before continuing.

Let's return to the example of the Geolocation API — this is a very simple API that consists of a few simple objects:

  • Geolocation, which contains three methods for controlling the retrieval of geo data.
  • Position, which represents the position of a device at a given time — this contains a Coordinates object that contains the actual position information, plus a timestamp representing the given time.
  • Coordinates, which contains a whole lot of useful data on the device position, including latitude and longitude, altitude, velocity and direction of movement, and more.

So how do these objects interact? If you look at our maps-example.html example (see it live also), you'll see the following code:

navigator.geolocation.getCurrentPosition(function(position) {
  var latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
  var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    disableDefaultUI: true
  }
  var map = new google.maps.Map(document.querySelector("#map_canvas"), myOptions);
});

Note: When you first load up the above example, you should be given a dialog box asking if you are happy to share your location with this application (see the They have additional security mechanisms where appropriate section later in the article). You need to agree to this to be able to plot your location on the map. If you still can't see the map, you may need to set your permissions manually; you can do this in various ways depending on what browser you are using; for example in Firefox go to > Tools > Page Info > Permissions, then change the setting for Share Location; in Chrome go to Settings > Privacy > Show advanced settings > Content settings then change the settings for Location.

We first want to use the Geolocation.getCurrentPosition() method to return the current location of our device. The browser's Geolocation object is accessed by calling the Navigator.geolocation property, so we start off by using

navigator.geolocation.getCurrentPosition(function(position) { ... });

This is equivalent to doing something like

var myGeo = navigator.geolocation;
myGeo.getCurrentPosition(function(position) { ... });

But we can use the dot syntax to chain our property/method access together, reducing the number of lines we have to write.

The Geolocation.getCurrentPosition() method only has a single mandatory parameter, which is an anonymous function that will run when the device's current position has been successfully retrieved. This function itself has a parameter, which contains a Position object representing the current position data.

Note: A function that is taken by another function as an argument is called a callback function.

This pattern of invoking a function only when an operation has been completed is very common in JavaScript API — making sure one operation has completed before trying to use the data the operation returns in another operation. These are called asynchronous operations. Because getting the device's current position relies on an external component (the device's GPS or other geolocation hardware), we can't guarantee that it will be done in time to just immediately use the data it returns. Therefore, something like this wouldn't work:

var position = navigator.geolocation.getCurrentPosition();
var myLatitude = position.coords.latitude;

If the first line had not yet returned its result, the second line would throw an error, because the position data would not yet be available. For this reason, API involving synchronous operations are designed to use callback functions, or the more modern system of Promises, which were made available in ECMAScript 6 and are widely used in newer API.

We are combining the Geolocation API with a third party API — the Google Maps API — which we are using to plot the location returned by getCurrentPosition()on a Google Map. We make this API available on our page by linking to it — you'll find this line in the HTML:

<script type="text/javascript" src="https://maps.google.com/maps/API/js?key=AIzaSyDDuGt0E5IEGkcE6ZfrKfUtE9Ko_de66pA"></script>

To use the API, we first create a LatLng object instance using the google.maps.LatLng() constructor, which takes our geolocated Coordinates.latitude and Coordinates.longitude values as parameters:

var latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

This object is itself set as the value of the center property of an options object that we've called myOptions. We then create an object instance to represent our map by calling the google.maps.Map() constructor, passing it two parameters — a reference to the <div> element we want to render the map on (with an ID of map_canvas), and the options object we defined just above it.

var myOptions = {
  zoom: 8,
  center: latlng,
  mapTypeId: google.maps.MapTypeId.TERRAIN,
  disableDefaultUI: true
}

var map = new google.maps.Map(document.querySelector("#map_canvas"), myOptions);

With this done, our map now renders.

This last block of code highlights two common patterns you'll see across many API. First of all, API objects commonly contain constructors, which are invoked to create instances of those objects that you'll use to write your program. Second, API objects often have several options available that can be tweaked to get the exact environment you want for your program. API constructors commonly accept options objects as parameters, which is where you'd set such options.

Note: Don't worry if you don't understand al the details of this example immediately. We'll cover using third party API in a lot more detail in a future article.

它们有可识别的入口点

When using an API, you should make sure you know where the entry point is for the API. In The Geolocation API, this is pretty simple — it is the Navigator.geolocation property, which returns the browser's Geolocation object that all the useful geolocation methods are available inside.

The Document Object Model (DOM) API has an even simpler entry point — its features tend to be found hanging off the Document object, or any instance of an HTML element that you want to affect in some way, for example:

var em = document.createElement('em'); // create a new em element
var para = document.querySelector('p'); // reference an existing p element
em.textContent = 'Hello there!'; // give em some text content
para.appendChild(em); // embed em inside para

Other API have slightly more complex entry points, often involving creating a specific context for the API code to be written in. For example, the Canvas API's context object is created by getting a reference to the <canvas> element you want to draw on, and then calling its HTMLCanvasElement.getContext() method:

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

Anything that we want to do to the canvas is then achieved by calling properties and methods of the content object (which is an instance of CanvasRenderingContext2D), for example:

Ball.prototype.draw = function() {
  ctx.beginPath();
  ctx.fillStyle = this.color;
  ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
  ctx.fill();
};

Note: You can see this code in action in our bouncing balls demo (see it running live also).

它们使用事件来处理状态的变化

We already discussed events earlier on in the course, in our Introduction to eventsarticle — this article looks in detail at what client-side Web events are and how they are used in your code. If you are not already familiar with how client-side Web API events work, you should go and read this article first before continuing.

Some Web API contain no events, but some contain a number of events. The handler properties that allow us to run functions when events fire are generally listed in our reference material in separate "Event handlers" sections. As a simple example, instances of the XMLHttpRequest object (each one represents an HTTP request to the server to retrieve a new resource of some kind) have a number of events available on them, for example the load event is fired when a response has been successfully returned containing the requested resource, and it is now available.

The following code provides a simple example of how this would be used:

var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();

request.onload = function() {
  var superHeroes = request.response;
  populateHeader(superHeroes);
  showHeroes(superHeroes);
}

Note: You can see this code in action in our ajax.html example (see it live also).

The first five lines specify the location of resource we want to fetch, create a new instance of a request object using the XMLHttpRequest() constructor, open an HTTP GET request to retrieve the specified resource, specify that the response should be sent in JSON format, then send the request.

The onload handler function then specifies what we do with the response. We know the response will be successfully returned and available after the load event has required (unless an error occurred), so we save the response containing the returned JSON in the superHeroes variable, then pass it to two different functions for further processing.

它们在适当的地方有额外的安全机制

WebAPI features are subject to the same security considerations as JavaScript and other Web technologies (for example same-origin policy), but they sometimes have additional security mechanisms in place. For example, some of the more modern WebAPI will only work on pages served over HTTPS due to them transmitting potentially sensitive data (examples include Service Workers and Push).

In addition, some WebAPI request permission to be enabled from the user once calls to them are made in your code. As an example, you may have noticed a dialog like the following when loading up our earlier Geolocation example:

The Notifications API asks for permission in a similar fashion:

These permission prompts are given to users for security — if they weren't in place, then sites could start secretly tracking your location without you knowing it, or spamming you with a lot of annoying notifications.

概要

At this point you should have a good idea of what API are, how they work, and what you can do with them in your JavaScript code. You are probably excited to start actually doing some fun things with specific API, so let's go! Next up, we'll look at manipulating documents with the Document Object Model (DOM).

文档标签和贡献者

 此页面的贡献者: ShirleyM, Ray-Eldath, tzigang, ander_fang
 最后编辑者: ShirleyM,