JavaScript HTTP 请求:XMLHttpRequest 和 Fetch API 指南
要使用 JavaScript 发出 HTTP 请求,您可以使用内置的 XMLHttpRequest 对象或使用更现代的 fetch 函数。下面是用两种方法之一发送 GET 请求的示例:
使用 XMLHttpRequest 对象:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();
使用 fetch 函数:
fetch('https://api.example.com/data')
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.log(error);
});
请注意,这只是发送 GET 请求的简单示例。根据您的需求,您可能需要设置其他选项(例如,设置请求头、发送 POST 请求等)或根据服务器响应进行进一步处理。
原文地址: https://www.cveoy.top/t/topic/bcPu 著作权归作者所有。请勿转载和采集!