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(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
这些示例使用 GET 请求从'https://api.example.com/data' 获取数据。您可以根据需要自定义请求方法(GET、POST 等)和其他参数(标头、正文等)。
请注意,这只是基本示例,实际应用中可能需要处理更多的错误和情况。
原文地址: https://www.cveoy.top/t/topic/jOy 著作权归作者所有。请勿转载和采集!