如何用Javascript发出HTTP请求?
可以使用XMLHttpRequest对象或fetch API来发出HTTP请求。
使用XMLHttpRequest对象:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
使用fetch API:
fetch('https://example.com/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
在上面的例子中,fetch API使用Promise来处理响应。首先,它会发出一个HTTP GET请求,然后将响应转换为JSON格式,并将结果打印到控制台。如果发生错误,它将捕获并打印错误
原文地址: https://www.cveoy.top/t/topic/gJgc 著作权归作者所有。请勿转载和采集!