<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>XMLHttpRequest API</title>
</head>
<body>
<script></script>
</body>
</html>

步驟3:

現在讓我們看看如何發出請求。首先,您需要初始化 XMLHttpRequest API 實例。具體操作如下

const xhr = new XMLHttpRequest();

現在,我們需要調用上面討論過的打開方法。

xhr.open(method, url);

我們需要將響應類型更改為 JSON,讓 API 知道我們需要 JSON 格式的數據:

xhr.responseType = 'json';

最后,我們需要發送請求。方法如下:

xhr.send();

您還需要處理 API 調用時收到的響應。為此,您需要在 XMLHttpRequest 實例上設置 onload 事件監聽器。

xhr.onload = () => {
console.log(xhr.response);
};

您也可以將整個 XMLHttpRequest 代碼封裝在一個承諾中,然后等待它,使其成為異步代碼。為了更好地理解,我還創建了一個快速演示。

const sendRequest = (method, url) => {

const promise = new Promise((resolve, reject) => {

const xhr = new XMLHttpRequest();

xhr.open(method, url);

xhr.responseType = 'json';

xhr.onload = () => {

if (xhr.status >= 400) {

reject(xhr.response);

}

resolve(xhr.response);

};

xhr.send();

});

return promise;

};

const getData = async () => {

try {

const res = await sendRequest('GET', 'https://rapidapi.com/guides/api/rest');

console.log(res);

} catch (err) {

console.log(err);

}

};

getData();

提交后:

{

"data": [

{

"id": 1,

"email": "john.doe@website.com",

"first_name": "John",

"last_name": "Doe"

},

{

"id": 2,

"email": "richard.doe@website.com",

"first_name": "Richard",

"last_name": "Doe"

},

{

"id": 3,

"email": "jane.doe@website.com",

"first_name": "Jane",

"last_name": "Doe"

}

]

}

支持

XMLHttpRequest API 支持所有現代網絡瀏覽器,包括 Chrome、Firefox、Edge、Opera 和 Safari。

原文鏈接:Interactive Guide to XMLHttpRequest API

上一篇:

2024年Python API框架:8個最佳開源選擇

下一篇:

Service Mesh 和 API Gateway 關系深度探討
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費