JavaScript HTTP 请求:XMLHttpRequest 和 Fetch API 指南
要通过 JavaScript 发出 HTTP 请求,您可以使用浏览器内置的 XMLHttpRequest 对象或者使用现代的 Fetch API。下面是使用这两种方法之一来发出 HTTP 请求的示例代码:
使用 XMLHttpRequest:
function makeHttpRequest(url, method, data, callback) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
};
xhr.send(data);
}
var apiUrl = 'https://api.example.com';
var requestData = JSON.stringify({ key: 'value' });
makeHttpRequest(apiUrl, 'POST', requestData, function(response) {
console.log(response);
});
使用 Fetch API:
function makeHttpRequest(url, method, data, callback) {
fetch(url, {
method: method,
body: data
})
.then(function(response) {
if (response.ok) {
return response.text();
}
throw new Error('Network response was not ok.');
})
.then(function(responseData) {
callback(responseData);
})
.catch(function(error) {
console.error('Error:', error);
});
}
var apiUrl = 'https://api.example.com';
var requestData = JSON.stringify({ key: 'value' });
makeHttpRequest(apiUrl, 'POST', requestData, function(response) {
console.log(response);
});
请注意,这些示例代码仅用于说明如何使用 JavaScript 发出 HTTP 请求。您需要根据自己的需求和 API 进行适当的更改。
原文地址: https://www.cveoy.top/t/topic/jvS 著作权归作者所有。请勿转载和采集!