JavaScript 发送 HTTP 请求:XMLHttpRequest 和 Fetch API
要发送一个请求,需要使用 XMLHttpRequest 对象或 fetch API。
使用 XMLHttpRequest 对象:
var 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));
AI 优化版
原文地址:https://www.cveoy.top/t/topic/mHBO 著作权归作者所有。请勿转载和采集!