JavaScript HTTP 请求:XMLHttpRequest 和 Fetch API 详解
要使用 JavaScript 发出 HTTP 请求,您可以使用内置的 XMLHttpRequest 对象或使用现代的 Fetch API。以下是使用这两种方法的示例代码:
使用 XMLHttpRequest 对象:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();
使用 Fetch API:
fetch('https://api.example.com/data')
.then(function (response) {
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok.');
})
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.log('Error:', error.message);
});
这些示例代码将向'https://api.example.com/data'发出 GET 请求,并在成功响应时打印响应数据。您可以根据自己的需求修改 URL 和请求类型(GET、POST 等)。
原文地址: https://www.cveoy.top/t/topic/bMet 著作权归作者所有。请勿转载和采集!