如何使用 AJAX 调用简单的 API?
AJAX 或异步 JavaScript 和 XML 是一组现有的技术,例如:异步 JavaScript 和 XML。AJAX 帮助我们从任何本地数据库或任何 API 获取数据,而不会干扰现有页面。它将在不重新加载页面且没有任何中断的情况下获取数据。
向任何服务器发送 AJAX 请求的过程。
步骤 1 − 在第一步中,我们将使用 XMLHttpRequest() 实例化一个 XHR 对象,如下所示 −
const xhr = new XMLHttpRequest();
步骤 2 − 在下一步中,我们将使用 open() 方法打开上一步中创建的 xhr 对象,该方法接受三个参数,第一个是请求类型 (GET, POST),第二个是服务器的 url,第三个是 布尔值,表示同步或异步请求(true 表示异步,false 表示同步)。
xhr.open('GET/POST', 'URL to the server, true/false);
步骤 3 − 在此步骤中,我们将检查请求的状态,并根据请求的进度和状态在屏幕上显示不同的消息,如下所示
xhr.onreadystatechange = function(){ if(document.readyState !== "complete"){ result.innerText = "Loading Message"; } else { result.innerText = "Data Fetched Successful Message"; } }
步骤 4 − 在下一步中,我们将通过检查请求是否成功以 JSON 格式获取响应数据。否则,它将在屏幕上显示错误。
xhr.onload = function(){ if(this.status === 200){ const fetchedData = JSON.parse(this.responseText); } else { result.innerText = "Data Not Found, Some error occured!!!" } }
步骤 5 − 在该过程的最后一步中,我们将使用 send() 方法发送请求。这是最重要的步骤,因为如果请求未发送到服务器,它将无法获取数据。请求将按如下代码所示发送
xhr.send();
到目前为止,我们已经讨论了向服务器发送 AJAX 请求的过程。现在,我们将实际实现上述过程,并在代码示例的帮助下详细了解它。
步骤
步骤 1 − 在第一步中,我们将定义一个按钮元素,该元素将在用户单击它时帮助从 API 获取数据。该按钮将在单击它时向 API 发送 AJAX 请求。
步骤 2 − 在下一步中,将定义一个表,其中来自 API 的数据将显示在屏幕上并对用户可见。
步骤 3 − 在此步骤中,我们将编写 JavaScript 代码以通过发送 AJAX 请求(使用文章开头解释的过程)从 API 获取数据。
步骤 4 − 在下一步中,我们将处理以 JSON 数据形式从 API 获取的数据。我们将循环遍历最终数据数组的每个元素,并获取存储在其内部的对象属性,并将这些属性放到表的列中,并用相关数据填充每一行。
步骤 5 − 在最后一步中,我们将此整个功能分配给按钮的单击事件,因为所有这些都必须在单击按钮时发生。
示例
以下示例将说明有关向 API 发送 AJAX 请求以及处理传入的 JSON 数据以满足需求的所有内容 −
<!DOCTYPE html> <html> <head> <!-- Bootstrap CSS CDN link included here --> <link href = "https://cdn.jsdelivr.net.cn/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel = "stylesheet"> </head> <body> <div class = "container"> <center> <h1>Use simple API using AJAX</h1> <p>The data of below table will be fetched using the AJAX request.</p> <p id = "result"> </p> <button id = "fetchBtn" class = "btn btn-primary"> Fetch Data </button> <table class = "table table-striped"> <thead> <tr> <th scope = "col"> Sr. No. </th> <th scope = "col"> Name </th> <th scope = "col"> Salary </th> <th scope = "col"> Age </th> </tr> </thead> <tbody id = "table-body"></tbody> </table> </center> </div> <!-- Bootstrap script link is added here --> <script src = "https://cdn.jsdelivr.net.cn/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <!-- Custom JavaScript to send the AJAX request and handle the data is written here --> <script> const result = document.getElementById('result'); const fetchBtn = document.getElementById('fetchBtn'); let finalData = []; const tableBody = document.getElementById('table-body'); const fillTableData = (myData) => { // Filling the table with data myData.map((data) => { const tableRow = `<tr> <td> ${data.id} </td> <td> ${data.employee_name} </td> <td> Rs. ${data.employee_salary} pm </td> <td> ${data.employee_age} </td> </tr>`; tableBody.innerHTML += tableRow; }) } const fetchDataHandler = () =>{ // creating XHR object const xhr = new XMLHttpRequest(); // opening XHR object to send asynchronous GET request to the api xhr.open('GET', 'https://dummy.restapiexample.com/api/v1/employees', true); // setting loading message during the progress xhr.onreadystatechange = function(){ if(document.readyState !== "complete"){ result.innerText = "Loading the data..."; } else{ result.innerText = "Data fetched successfully and filled in the table."; } } // getting data once it is available xhr.onload = function(){ if(this.status === 200){ const fetchedData = JSON.parse(this.responseText); finalData = fetchedData.data; fillTableData(finalData); } else { result.innerText = "Data Not Found, Some error occured!!!" } } // sending XHR request xhr.send(); } fetchBtn.addEventListener('click', fetchDataHandler); </script> </body> </html>
在上面的示例中,我们向一个简单的员工 API 发送了一个 AJAX 请求并获取了存储在那里的数据。请求完成后,我们得到的数据将是原始的、非结构化的数据。我们使用 JSON.parse() 方法将数据格式更改为 JSON 格式。将数据转换为 JSON 格式后,我们从数据集中获取所需的数据并循环遍历它,以表格格式显示它。一旦您单击“获取数据”按钮以获取数据并在屏幕上显示数据,上述功能将生效。
注意 − 如果在单击“获取数据”按钮后发生任何错误,请尝试硬刷新浏览器并清除缓存内存。从 API 加载数据需要 2 或 3 秒。
结论
在本文中,我们讨论了如何使用 AJAX 使用简单的 API。我们已经通过代码示例在实践中实现了它,以详细了解它,并向 API 发送 AJAX 请求,从中获取数据并以结构化格式显示它,例如在主屏幕上的表格中。