JavaScript - 如何使用AJAX从外部API获取数据

527 阅读3分钟

异步JavaScript - 使用AJAX从外部API获取数据

AJAX是异步JavaScript和XML的缩写。它是一套用于在客户端和服务器之间发送和接收数据的网络技术。

Ajax允许你以异步方式提出请求,而不必重新加载页面。此外,Ajax可以发送和接收各种格式的信息,包括JSON、XML、HTML和文本文件。

在本教程中,为了展示Ajax是如何工作的,我们将创建一个JavaScript程序,从外部API获取数据,对其进行格式化,并返回随机的Chuck Norris笑话。

这很简单。Ajax走出去,得到笑话,然后把它们显示给用户。

前提条件

要跟上这个教程,你需要有以下的一些知识。

  • [JavaScript]
  • [HTML]
  • [骨架式CSS]
  • [API是如何工作的]
  • 一个代码编辑器(最好是[Visual Studio Code])

本教程的目标

本教程旨在创建一个网页,从Chuck Norris Jokes API获取随机笑话并显示给用户。

在本教程结束时,读者将知道如何调用外部API,获取数据并将结果显示在网页上。

首先,让我们来建立用户界面。

  • 创建一个新的HTML文件并将其保存为index.html
  • 使用下面给出的HTML模板。
<!DOCTYPE html>
<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>
  </head>
  <body></body>
</html>
  • 将标题改为你喜欢的标题。
  • 添加下面的链接标签,以包括Skeleton CSS CDN。骨架CSS有助于建立一个简单的、反应灵敏的用户界面。
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css"
  integrity="sha512-5fsy+3xG8N/1PV5MIJz9ZsWpkltijBI48gBzQ/Z2eVATePGHOkMIn+xTDHIfTZFVb9GMpflF2wOWItqxAP2oLQ=="
  crossorigin="anonymous"
  referrerpolicy="no-referrer"
/>
  • 创建一个带有输入和按钮的表单。
<div class="container">
  <form>
    <div>
      <label for="number"> Number of jokes to generate</label>
      <input id="number-of-jokes" type="number" id="number" />
    </div>

    <div>
      <button id="generate-jokes">Generate Jokes</button>
    </div>
  </form>
</div>
  • 创建一个有序的列表(ol ),让笑话在表单下面呈现。

  • 创建一个JavaScript文件并将其保存为index.js

  • 在HTML文件中包括index.js

  • 你的HTML文件应该看起来像这样👇。

<!DOCTYPE html>
<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" />

    <!-- Skeleton CSS -->
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css"
      integrity="sha512-5fsy+3xG8N/1PV5MIJz9ZsWpkltijBI48gBzQ/Z2eVATePGHOkMIn+xTDHIfTZFVb9GMpflF2wOWItqxAP2oLQ=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    />

    <title>Getting Jokes from External API</title>
  </head>
  <body>
    <div class="container">
      <h2>Asynchronous JS Joke Generator</h2>
      <form>
        <div>
          <label for="number"> Number of jokes to generate</label>
          <input id="number-of-jokes" type="number" id="number" />
        </div>

        <div>
          <button id="generate-jokes">Generate Jokes</button>
        </div>
      </form>
      <ol id="jokes"></ol>
    </div>

    <script src="./index.js"></script>
  </body>
</html>

JavaScript

  • 打开index.js
  • 从DOM中抓取这个按钮。
const button = document.querySelector("#generate-jokes");
  • 给按钮添加一个事件监听器来监听点击。
button.addEventListener("click", generateNewJokes);

准备好AJAX请求

  • 为点击事件创建一个名为generateNewJokes() 的函数。
  • 从UI中抓取#number-of-jokes 元素并将其分配给一个变量。
  • 创建一个名为request的变量并将其设置为一个新的XHR对象。
function generateNewJokes(e) {
  const newXHRRequest = new XMLHttpRequest();
  const numberOfJokes = document.querySelector("#number-of-jokes").value;
}

"XMLHttpRequest (XHR)对象是用来与服务器交互的。你可以从一个URL中检索数据,而不需要进行全页面刷新。这使得网页可以只更新页面的一部分而不干扰用户正在做的事情"。

  • generateNewJokes 函数中,创建一个对象,newXHRRequest.open() ,它需要三个参数。
  1. HTTP请求方法,在这个例子中是GET方法
  2. 一个DOMString,代表请求被发送到的URL。
  3. Async是一个可选的布尔值,设置为true ,表示该操作是异步的。
newXHRRequest.open(
  "GET",
  `http://api.icndb.com/jokes/random/${numberOfJokes}`,
  true
  // the numbers of jokes is appended to the url after a forward slash to specify the numbers of jokes to fetch from the server
);
  • 设置newXHRRequest.onload 为一个函数。
newXHRRequest.onload = function () {};

在newXHRRequest.onload函数中

  • 检查XHR STATUS是否返回200。
  • 将JSON格式的响应文本解析为一个变量。
  • 初始化一个变量并将其设置为空(我们将用它来串联响应)。
  • 检查响应类型是否返回成功。
  • 如果响应类型返回 "success",创建一个forEach循环,循环浏览响应的值,得到笑话。然后将笑话附加到一个列表标签内(使用模板字面的灵活格式化)。
  • 如果响应类型不是成功,在列表项中追加一个错误响应。
  • innerHTMLol ,并将笑话的类别设置为输出。
if (this.status === 200) {
  const myJokes = JSON.parse(this.responseText);

  let output = "";

  if (myJokes.type === "success") {
    myJokes.value.forEach(function (joke) {
      output += `<li>${joke.joke}</li>`;
    });
  } else {
    output += `<li>Sorry! Couldn't get jokes</li>`;
  }

  document.querySelector("#jokes").innerHTML = output;
}
  • 然后,发送newXHRRequest。
newXHRRequest.send();

请注意。

为了防止按钮执行其默认动作,在点击按钮时调用的函数上使用e.preventDefault()

查克-诺里斯笑话API只能生成随机笑话;这就是API的工作方式。

你可以根据你的需要来改变输出的风格。

最后的JavaScript文件应该是这样的👇。

const button = document.querySelector("#generate-jokes");

button.addEventListener("click", generateNewJokes);

function generateNewJokes(e) {
  const newXHRRequest = new XMLHttpRequest();
  const numberOfJokes = document.querySelector("#number-of-jokes").value;

  newXHRRequest.open(
    "GET",
    `http://api.icndb.com/jokes/random/${numberOfJokes}`,
    true
  );

  newXHRRequest.onload = function () {
    if (this.status === 200) {
      const myJokes = JSON.parse(this.responseText);
      let output = "";
      if (myJokes.type === "success") {
        myJokes.value.forEach(function (joke) {
          output += `<li>${joke.joke}</li>`;
        });
      } else {
        output += `<li>Sorry! Couldn't get jokes</li>`;
      }

      document.querySelector("#jokes").innerHTML = output;
    }
  };

  newXHRRequest.send();

  e.preventDefault();
}

最终的应用程序将看起来像这样。

Output

结论

使用互联网查克-诺里斯数据库(ICNDB)的API是一个简单的方法来展示如何使用AJAX从外部API获取数据。例如,Ajax使用GET方法从Internet Chuck Norris笑话数据库中提取笑话。

需要注意的一点是,不是所有的API都以同样的方式工作,它们处理请求和响应的方式也不尽相同。因此,当务之急是检查打算使用的API的文档。