使用 AJAX 和自定義 HTTP 庫發起 Get 請求
我們將學習如何透過建立自定義 HTTP 庫來使用 AJAX 發起 Get 請求。
在我們開始本教程之前,讓我們先了解一下 Get 請求和 AJAX。Get 請求用於從 API(應用程式程式設計介面)獲取或提取資料。AJAX 代表非同步 JavaScript 和 XML。AJAX 允許我們在不重新載入網頁的情況下載入或更新新資料。
例如,如果您曾經使用過 ReactJs,它會在不重新載入網頁的情況下更新資料。如果我們在每次資料更新時都重新載入網頁,可能會導致糟糕的使用者體驗。以 Twitter 為例,它會在不重新載入網頁的情況下更新點贊和轉發次數。假設每當任何推文獲得點贊時都重新載入網頁,這會導致糟糕的使用者體驗。
在 JavaScript 中,開發人員通常使用 fetch() 或 Axios() 模組來發起 Get 請求。在本教程中,我們將建立自己的 HTTP 庫來發起 Get 請求。
語法和演算法
步驟 1 - 建立 CustomHTTPLibrary 函式,並使用 XMLHTTPRequest 方法初始化新的 XML HTTP 請求。
this.http = new XMLHttpRequest();
步驟 2 - 將 GetRequest 新增到 CustomHTTPLibrary() 函式的原型中。同時,用函式初始化 GetRequest。
customHTTPLibrary.prototype.GetRequest = function (basURL, callBackFunction) {
// code to manage the GET request
}
在上面的語法中,baseURL 是要獲取資料的 URL,callBackFunction 是一個用於執行成功響應或錯誤的函式。
步驟 3 - 在 GetRequest 函式中,當 HTTP 載入時呼叫箭頭函式。
this.http.onload = () => {
}
步驟 4 - 在 onload 函式中,檢查響應的狀態。如果響應狀態為 200,則資料獲取成功,並使用響應呼叫回撥函式。如果響應狀態碼不是 200,則表示存在某些錯誤,並使用錯誤呼叫回撥函式。
if (selfScope.http.status === 200) {
// call the callback function with a response
} else {
// call the callback function with the error
}
步驟 5 - 最後,我們需要傳送 http 請求。
this.http.send();
步驟 6 - 我們的自定義 HTTP 庫已準備好發起 Get 請求。現在,我們需要使用該庫。
步驟 7 - 建立 CustomHTTPLibrary 函式的新例項。
const httpLibrary = new customHTTPLibrary;
步驟 8 - 現在,使用 httpLibrary 物件從 API 發起 Get 請求。
httpLibrary.GetRequest(URL,
(error, data) => {
// handle error and data
});
在上面的語法中,URL 是要獲取資料的 API。
示例
在下面的示例中,我們建立了一個自定義 HTTP 庫來使用 AJAX 發起 Get 請求。首先,我們建立了 HTTP 庫,然後透過初始化庫的例項來使用它。
此外,使用者還可以檢視管理從 API 獲取的響應中的錯誤和資料的程式碼。
<html>
<body>
<h2>Making the <i>custom HTTP library</i> to Make a Get request using AJAX.</h2>
<div id = "output"> </div>
<script>
let output = document.getElementById('output');
function customHTTPLibrary() {
// Initialising new XMLHttpRequest method
this.http = new XMLHttpRequest();
}
// Make an HTTP GET Request
customHTTPLibrary.prototype.GetRequest = function (basURL, callBackFunction) {
this.http.open('GET', basURL, true);
let selfScope = this;
this.http.onload = () => {
if (selfScope.http.status === 200) {
callBackFunction(null, selfScope.http.responseText);
} else {
callBackFunction('Error in fetching the data : ' + selfScope.http.status);
}
}
// At last, send the request
this.http.send();
}
// Instantiating easyHTTP
const httpLibrary = new customHTTPLibrary;
httpLibrary.GetRequest('https://api.publicapis.org/entries',
(error, data) => {
if (error) {
console.log(err);
} else {
data = JSON.parse(data);
for (let item of data.entries) {
output.innerHTML += data;
}
}
});
</script>
</body>
</html>
我們學習瞭如何透過建立自定義 HTTP 庫來使用 AJAX 發起 Get 請求。此外,使用者還可以嘗試透過建立自定義 HTTP 庫來使用 AJAX 發起 POST 請求。
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP