JavaScript HTTP 请求:XMLHttpRequest 和 Fetch API
要使用 JavaScript 发出 HTTP 请求,你可以使用内置的 XMLHttpRequest 对象或者使用更现代化的 fetch 函数。我将向你展示两种方法:
使用 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 函数:
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'获取数据。你可以将 URL 替换为你要请求的 API 地址。这些代码将发出 GET 请求,并在收到响应后以 JSON 格式处理数据。你可以根据需要进行其他定制和错误处理。
原文地址: https://www.cveoy.top/t/topic/WHh 著作权归作者所有。请勿转载和采集!