如何使用 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/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/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 請求,從中獲取資料並以結構化格式顯示它,例如在主螢幕上的表格中。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP