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);
});
这些示例都使用 GET 请求从'https://api.example.com/data' 获取数据。您可以根据需要自行更改 URL 和请求类型(GET、POST 等)。请注意,此代码在浏览器环境下运行,如果在 Node.js 环境中使用,请考虑使用适用于 Node.js 的模块(如http 或 axios)来发出 HTTP 请求。
原文地址: http://www.cveoy.top/t/topic/bLyL 著作权归作者所有。请勿转载和采集!