JavaScript HTTP 请求:XMLHttpRequest 和 Fetch API 示例
你可以使用 JavaScript 中的内置对象 'XMLHttpRequest' 或现代浏览器中的 'fetch' 函数来发出 HTTP 请求。以下是使用这两种方法的示例:
使用 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);
});
请注意,这只是简单的示例代码,实际使用中可能需要进行错误处理、设置请求头、发送 POST 请求等等。
原文地址: https://www.cveoy.top/t/topic/32q 著作权归作者所有。请勿转载和采集!