
企業如何快速建立自己的專屬AI大模型?
<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