JavaScript 发出 HTTP 请求 - XMLHttpRequest 和 Fetch
使用 JavaScript 发出 HTTP 请求可以使用 'XMLHttpRequest' 对象或 'fetch' 函数。以下是使用这两种方法之一的示例:
使用 XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/api', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();
使用 fetch:
fetch('http://example.com/api')
.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);
});
这些示例中的 'http://example.com/api' 表示要发送请求的 URL。您可以根据实际情况更改它。
原文地址: https://www.cveoy.top/t/topic/RzE 著作权归作者所有。请勿转载和采集!